Just as code contract preconditions control what information is passed to the method under contract, code contract postconditions control what information the method under contract returns to the calling code. You can, therefore, specify that the method will never return a null value or an empty dataset, for example. The actual condition does not matter; this is something that will change on a case-by-case basis. The important thing to remember here is that this code contract allows you to have more control over the data returned by your code.
Assume that the method under contract needs to ensure that the value returned will always be greater than zero. Using a code contract postcondition, we can easily enforce this rule.
using
statement to the top of your Recipes
class:using System.Diagnostics.Contracts;
Recipes
class, add a method called NeverReturnZero()
and pass an integer parameter to this method:public static class Recipes { public static int NeverReturnZero(int iNonZeroValue) { } }
Ensures
. This is quite descriptive of its function. The code contract ensures that a specific method result is never returned. You can see this in the signature of the Contract.Ensures
method. The postcondition, therefore, ensures that the result of this method will never be zero:public static int NeverReturnZero(int iNonZeroValue) { Contract.Ensures(Contract.Result<int>() > 0, "The value returned was not greater than zero"); return iNonZeroValue - 1; }
using
statements:using static System.Console; using static Chapter8.Recipes;
using
statement, you can just call the method name in the Recipes
class directly. Pass the NeverReturnZero()
method a value of 1
:try { NeverReturnZero(1); } catch (Exception ex) { WriteLine(ex.Message); ReadLine(); }