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.
We will create a static class for our extension method and then use the ForAll
code contract to validate the List
collection.
using
statement to the top of your Recipes.cs
class file:using System.Diagnostics.Contracts;
ExtensionMethods
and add it to your Recipes.cs
class file:public static class ExtensionMethods { }
ContainsInvalidValue()
that takes the given list of anonymous type T
and an invalid value to check as type T
as parameters:public static bool ContainsInvalidValue<T>(this List<T> value, T invalidValue) { }
ForAll
wrapped in a try
catch
statement that checks the existence of the given parameter in the list:try { Contract.Assert(Contract.ForAll(value, n => !value.Contains(invalidValue)), "Zero values are not allowed"); return false; } catch { return true; }
public static class ExtensionMethods { public static bool ContainsInvalidValue<T>(this List<T> value, T invalidValue) { try { Contract.Assert(Contract.ForAll(value, n => !value.Contains(invalidValue)), "Zero values are not allowed"); return false; } catch { return true; } } }
using
statement to the Program.cs
class to bring the Chapter8
class into scope:using Chapter8;
List<int> intList = new List<int>(); int[] arr; intList.AddRange(arr = new int[] { 1, 3, 2, 6, 0, 5 }); if (intList.ContainsInvalidValue(4)) WriteLine("Invalid integer Value"); else WriteLine("Valid integer List");
List<string> strList = new List<string>(); string[] arr2; strList.AddRange(arr2 = new string[] { "S", "A", "Z" }); if (strList.ContainsInvalidValue("G")) WriteLine("Invalid string Value"); else WriteLine("Valid string List");