Using code contracts in extension methods
The previous recipes illustrated how a developer might create various code contracts to secure your code from unexpected input and output, but let's look at how a developer could leverage code contracts. The idea of extension methods come to mind, where we create code that can be used throughout your project to perform actions that are often used.
Let's use the code contract ForAll method. This has an impact on a collection, so naturally, its use in extension methods leads us to a possible implementation. In this recipe, we will create an extension method that uses a code contract to validate the list we have just created.
Getting ready
We will create a static class for our extension method and then use the ForAll code contract to validate the List collection.
How to do it…
Before you go on, ensure that you have added the code contracts
usingstatement to the top of yourRecipes.csclass file:using System.Diagnostics.Contracts;
Create a new static class...