Code contracts are used
when you want to call and run a method under certain pre-conditions,
post-conditions and running conditions (invariants).
For instance let’s say you want to call the below “Add” method under the following restrictions: -
- Pre-condition:- “Add” method can only be called when “num1” and “num2” values are greater than zero.
- Post-Condition: - The value returned from “Add” method cannot zero or less than zero.
public int Add(int num1, int num2)
{
return num1 + num2;
}
So by using code contracts you can achieve the same by putting the below code.
public int Add(int num1, int num2)
{
Contract.Requires((num1
> 0) && (num2 > 0)); // precondition
Contract.Ensures(Contract.Result<int>()
> 0); // post condition
return num1 + num2;
}
So if you try to call the “Add” method with zero values you should get a contract exception error as shown in the below figure.
Code contract only do dynamic checks
The best part of code contract is it also does static checking. Once you build the code the contract analysis check runs to see if any pre-conditions, post-conditions or invariants (runningconditions) are violated.
For instance you can see in the below figure how the error is shown in the error window list. The “Add” method is called with zero value and the code contract shows the error stating that this call is invalid in the IDE itself.