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.
So by using code contracts you can achieve the same by putting the below code.
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.