15

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?

George Mauer
  • 117,483
  • 131
  • 382
  • 612

3 Answers3

17

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.

JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
2

Expanding on JSBangs' answer:

You must check the "Perform Runtime Contract Checking" box here:

enter image description here

(I also checked the "Static Checking > Peform Static Contract Checking" box)

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    Also of note, the [code contracts visual studio extensions](http://visualstudiogallery.msdn.microsoft.com/02de7066-b6ca-42b3-8b3c-2562c7fa024f) which will attempt to parse your contracts and inform you of issues before you even build. – George Mauer Sep 24 '13 at 22:42
0

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
  • 1,404
  • 8
  • 15