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…

  1. Before you go on, ensure that you have added the code contracts using statement to the top of your Recipes.cs class file:
    using System.Diagnostics.Contracts;
  2. Create a new static class called ExtensionMethods and add it to your Recipes.cs class file:
    public static class ExtensionMethods
    {
        
    }
  3. Next, add an extension method called 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)
    {    
    
    }
  4. Inside our extension method, add code contract 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;
    }
  5. Once you have added all the code to your extension method, it should look like this:
    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;
            }
        }
    }
  6. In the console application, add the relevant using statement to the Program.cs class to bring the Chapter8 class into scope:
    using Chapter8;
  7. As we did earlier, create a simple list, but this time, call the extension method that is exposed via the static extension methods class on the list. We will now be able to directly validate our list via the use of extension methods and code contracts:
    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");
  8. Running the application will result in the following output:
    How to do it…
  9. As we are using an anonymous type here, we can easily call this extension method on lists containing different types. Here is an example of an implementation on a list of strings:
    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");
  10. Running the application again will result in the following output:
    How to do it…

How it works…

We can see that using code contracts along with other powerful features of C# allows us to utilize very powerful code checking and validation techniques. The extension methods can be used throughout your project to perform frequent validation or other code logic specific to your project.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.126