views:

205

answers:

2

After reading about the System.Diagnostics.Contracts.Contract static class that has been influenced by the awesomeness of Spec# I was thrilled and immediately started peppering my code with calls to Contract.Requires() and Contract.Ensures().

I guess it's just because my code is so super-awesome and bug-free that checking that those calls actually did something just didn't come up until recently. A bug slipped through and I came to the realization that these calls do not do anything! I would have thought that they at least throw an exception when the condition is violated but no such luck.

Am I missing something? Does anyone know what the heck is the point?

+6  A: 

From the Contract Class page at MSDN:

You must use a binary rewriter to insert run-time enforcement of contracts. Otherwise, contracts such as the Contract.Ensures method can only be tested statically and will not throw exceptions during run time if a contract is violated. You can download the binary rewriter CCRewrite from Code Contracts on the MSDN DevLabs Web site. CCRewrite comes with a Visual Studio add-in that enables you to activate run-time contract enforcement from the project Properties page. The binary rewriter and the Visual Studio add-in do not ship with Visual Studio 2010 or the Windows SDK.

JSBangs
+1  A: 

If you want the .Requires call to throw an error you need to set an option in project settings or use .Requires<T> call

unclepaul84
What do you mean? What option? I am using .Requrires()
George Mauer
Under project properties, head to the "Code Contracts" tab.
Porges