Following is .NET interview questions on code contract in .NET.
Code contracts: -
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.
Do code contract perform only 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.
Code contract part of Visual Studio or not: -
No, code contract is not part of visual studio it’s a separate setup. Once you install this setup it creates a separate tab in “project properties” as shown below. You can then enable static and dynamic checking by clicking on the below check boxes as shown in the below figure.