10

I am trying to add validation for my type at compilation time using Contract but unfortunately it do not work. For example code below do not give compiler error while compiling project. Should I enable something?

Contract.Assert(false, "Invalid state!");
Tomas
  • 17,551
  • 43
  • 152
  • 257

1 Answers1

9

Yes, you need to enable the static checking. Go into the project properties and visit the "Code Contracts" tab. Of course you'll need to have installed the static checker extension first, which IIRC is only available for Visual Studio Ultimate. See the user documentation for details of the exact options available.

Note that this happens after the initial compilation phase, so sometimes you'll see a delay between the first part of the build and the results of the static checker. (It's not really a "compiler" error - it's a "contract checking" error.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    A [Code Contracts](http://research.microsoft.com/en-us/projects/contracts/) package contains the static checker for contracts (`cccheck.exe`) which works with almost every version of VS, except Express. If you have the Ultimate version, great, if you don't - no worries, contracts work with Professional just fine. :) – Patryk Ćwiek Jun 19 '12 at 11:19
  • user documentation no longer exists Jon. project was moved to github. Please update your link – John Demetriou Apr 05 '17 at 15:04
  • 1
    @JohnDemetriou: Updated, but in future if you know the new link already, it would be better just to edit the answer to update the link. – Jon Skeet Apr 05 '17 at 15:09
  • @JonSkeet I am with mobile and reading while drinking coffee at the beach :) . It was a bit confusing to get around in the github project of Code Contracts and that this would benefit more people as your edit would be faster than mine. I know you have like a trillion bots constantly reading and replying :) – John Demetriou Apr 05 '17 at 15:12