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.
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.
using
statement to the top of your Recipes.cs
class file:using System.Diagnostics.Contracts;
ValidateList()
to your class and pass a List<int>
collection to it:public static void ValidateList(List<int> lstValues) { }
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"); }
using
statement to the Program.cs
class to bring the static class into scope:using static Chapter8.Recipes;
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(); }
18.118.93.175