Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

Using runtime checking of code contracts in Visual Studio 2010

In my last posting about code contracts I introduced how to check input parameters of randomizer using static contracts checking. But you can also compile code contracts to your assemblies and use them also in runtime. In this posting I will show you simple example about runtime checking of code contracts.

NB! If you want to play with code and try out things described here feel free to download example solution. if you are speaker and want to use this solution as a part of your sessions then feel free to do so, but don’t forget to refer me and this blog as source of this solution. And please let me know about your session. As a speaker I am very interested about it. :)

To see how code contracts are checked at runtime we have to enable runtime checking from project properties. Make sure you have checked the box “Perform Runtime Contract Checking” and make sure you select “Full” from dropdown. These parts are in red box on the screenshot below.

Visual Studio 2010 Code Contracts: Runtime Checking is turned on and checks are made only in public surface
Visual Studio 2010 settings for code contracts.
Runtime Checking is turned on and checks are made only in public surface.
Click on image to see it at original size.
 

Save project settings. Then compile code and run it. As soon as code execution hits the call to GetRandomFromRangeContracted() exception is thrown. If you are not currently playing with solution referred above take a look at the following screenshot.

Visual Studio 2010 Code Contracts: Exception of type ContractException is thrown when contract is violated
Visual Studio 2010 runtime checking of code contracts.
Exception of type ContractException is thrown when contract is violated.
Click on image to see it at original size.
 

The exact type of exception is ContractException and it is defined in System.Diagnostics.Contracts.__ContractsRuntime namespace. In our example the message of exception is following:

"Precondition failed: min < max  Min must be less than max"

Besides the description we inserted for the case contract violation the message also contains violated contract type. In this case the type of contract is Precondition.

Conclusion

Using runtime checking of code contracts enables you to take code contracts with your code and have them checked every time when your methods are called. This way you can assure that all conditions are met to run method or exception is thrown and calling system has to handle the situation.

Comments

No Comments