Creating code contract Result method

Sometimes, we simply want a way to validate the result of a method. We want to be able to check what is returned and validate it against some or the other condition. It is here that the code contract Result can be used. It will inspect the value returned by the method under contract against the contract specified, and then it will succeed or fail.

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. In the Recipes class, add a new method called ValidateResult() that takes two integer values as parameters:
    public static int ValidateResult(int value1, int value2)
    {
        
    }
  3. To this method, add the code contract Result that checks the resultant value of the method. It has to be mentioned that the code contract Result can never be used in a void method. This is obvious, because the very purpose of this code contract is to examine and validate the result of a method. You will also notice that the code contract Result method is used in conjunction with the Contract.Ensures method. The format of Contract.Result is made up of the return type <int>() and the condition >= 0 that the return value needs to adhere to:
    public static int ValidateResult(int value1, int value2)
    {
        Contract.Ensures(Contract.Result<int>() >= 0, "Negative result not allowed");
        return value1 - value2;
    }
  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. Add the call to the static method under contract and pass to it parameters that will cause the code contract to throw an exception. In this case, we are passing 10 and 23, which will result in a negative result being returned from the ValidateResult() method:
    try
    {
        WriteLine(ValidateResult(10, 23));
    }
    catch (Exception ex)
    {
        WriteLine(ex.Message);
    }
    ReadLine();
  6. Finally, run the console application and inspect the result returned to the console output window:
    How to do it…

How it works…

You will see that the code contract has inspected the resultant value of the ValidateResult() method and found that it contravenes the contract. An exception is then thrown and displayed in the console window.

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

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