Creating code contract ForAll method

If this code contract sounds like it is validating some or the other collection, then you would be correct. The code contract ForAll will perform validation of IEnumerable collections. This is very handy, because as a developer, you do not need to do any kind of iteration over the collection and writing validation logic. This contract does it for you.

Getting ready

We will create a simple list of integers and populate the list with values. Our code contract will validate that the list does not contain any zero values.

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. Add a method called ValidateList() to your class and pass a List<int> collection to it:
    public static void ValidateList(List<int> lstValues)
    {
        
    }
  3. Inside the ValidateList() method, add the Contract.ForAll contract. Interestingly, you will notice that we are using Contract.Assert here to check whether this list passes our contract conditions. The Contract.ForAll will use a lambda expression to check that none of the values contained in our list of integers equals zero:
    public static void ValidateList(List<int> lstValues)
    {
        Contract.Assert(Contract.ForAll(lstValues, n => n != 0), "Zero values are not allowed");
    }
  4. In the console application, add the relevant using statement to the Program.cs class to bring the static class into scope:
    using static Chapter8.Recipes;
  5. You can then add a simple list of integers containing at least one zero value and pass it to the ValidateList() method:
    try
    {
        List<int> intList = new List<int>();
        int[] arr;
        intList.AddRange(arr = new int[] { 1, 3, 2, 6, 0, 5});
        ValidateList(intList);
    }
    catch (Exception ex)
    {
        WriteLine(ex.Message);
        ReadLine();
    }
  6. Run the console application and inspect the results in the output:
    How to do it…

How it works…

We can see that the ForAll contract has worked exactly as we had expected. This is an extremely useful code contract to use, especially since you need not add copious amounts of boilerplate code to check the collection for various invalid values.

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

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