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.
Code contract dynamic checks or not
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.
Also see following .NET interview questions videos on about difference between Constant and Readonly.: -