Preconditions allow you to control exactly what the parameters need to look like before they are used in your method. This means that you can assume a lot of things about the data being sent to your method by the calling code. You can, for example, specify that a parameter should never be null or that a value must always be within a specific value range. Dates can be checked, and objects can be verified and vetted.
You have complete control over the data coming in to your method. It gives you the peace of mind to use that data once it has passed your contract without having to do additional checks.
Be sure that you have installed code contracts and that you have configured the settings correctly in the project properties, as described in the previous recipe.
Recipes
class, create a new method called ValueGreaterThanZero()
and have it take an integer as a parameter:public static class Recipes { public static void ValueGreaterThanZero(int iNonZeroValue) { } }
ValueGreaterThanZero()
method, type the start of the Contract
declaration, and you will notice that the code is underlined with a red squiggly line. Hold down Crtl + . (period) to bring up the suggestions for potential fixes. Click on the suggestion to add the using
statement for the code contracts to your class:public static void ValueGreaterThanZero(int iNonZeroValue) { Contract.Requires(iNonZeroValue >= 1, "Parameter iNonZeroValue not greater than zero"); }
using
statements:using static System.Console; using static Chapter8.Recipes;
using
statement, you can just call the method name in the Recipes
class directly. To see how code contracts work, pass a zero parameter to the method:try { ValueGreaterThanZero(0); } catch (Exception ex) { WriteLine(ex.Message); ReadLine(); }