Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




.NET interview questions: - What are code contracts? Does code contract only do dynamic checks?

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.

Helpful Website Url
http://questpond.com/
Share this article   |    Print    |    Article read by 6190 times
Author:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Related Articles:
Related Interview Questions: