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.
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.
using
statement to the top of your Recipes.cs
class file:using System.Diagnostics.Contracts;
Recipes
class, create a new method called ValidOutValue()
and pass an out
parameter called secureValue
to it:public static void ValidOutValue(out int secureValue) { }
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; }
using
statement to the Program.cs
class to bring the static class into scope:using static Chapter8.Recipes;
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();
18.118.137.67