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…
Before you go on, ensure that you have added the code contracts
using
statement to the top of yourRecipes.cs
class file:using System.Diagnostics.Contracts;
In the
Recipes
class, create a new method calledValidOutValue()
and pass anout
parameter calledsecureValue
to it:public static void ValidOutValue(out int secureValue) { }
Finally, add
Contract.ValueAtReturn
to the method. Interestingly, you will note that this needs to be contained inContract.Ensures
...