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 ...

Get C# Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.