Creating code contract ValueAtReturn method

The best example we can think of when using the code contract ValueAtReturn is out parameters. Personally, I do not use out parameters often, but there are times when you need to use them. Code contracts make provision for this, and you can check the value at the time it is returned.

Getting ready

We will create a simple method that subtracts a value from a parameter. The out parameter will be validated by the code contract, and the result will be output to the console window.

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, create a new method called ValidOutValue() and pass an out parameter called secureValue to it:
    public static void ValidOutValue(out int secureValue)
    {
        
    }
  3. Finally, add Contract.ValueAtReturn to the method. Interestingly, you will note that this needs to be contained in Contract.Ensures. This actually makes sense, because the code contract ensures that the value that we will return will adhere to a specific condition:
    public static void ValidOutValue(out int secureValue)
    {
        Contract.Ensures(Contract.ValueAtReturn<int>(out secureValue) >= 1, "The secure value is less or equal to zero");
        secureValue = secureValue - 10;
    }
  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. Then, add some code to call the ValidOutValue() method and pass an out parameter to it:
    try
    {
        int valueToCheck = 5;
        ValidOutValue(out valueToCheck);
        WriteLine("The value is not zero");
    }
    catch (Exception ex)
    {
        WriteLine(ex.Message);
    }
    ReadLine();
  6. Run the console application and inspect the results in the output window:
    How to do it…

How it works…

We can see that the out parameter has been successfully validated. As soon as the condition was not met, the code contract threw an exception that we were able to catch.

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

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