Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to install and use Code Contracts?

I have a basic question, might be it is so obvious but for some reason i can't seem to be successful with installing and using Code Contracts.

I've downloaded the package from MSDN, installed it following the online documentation but i still get an IDE warning for the below code statement:

Contract.Requires(inputParameter != "");

the IDE warning is:

"Method invocation is skipped. Compiler will not generate method invocation because the method is conditional, or it is partial method without implementation"

Anything I'm missing in the process of enabling Code Contracts? I'm using VS2010 Ultimate SP1

like image 872
NirMH Avatar asked Dec 19 '12 08:12

NirMH


2 Answers

Most likely this is due to Code Contracts not being configured in the project settings. If you go to your project properties, you should see a Code Contracts tab. On the tab, select the mode you are building in (Debug|Release|Both) and then turn on Code Contracts features by checking the appropriate check boxes.

I've seen the warning that you detail when Code Contracts are not set to Build.

If you don't see the Code Contracts tab, then you might need to install Code Contracts on your machine. Do this by downloading and installing the installer from here.

like image 129
Davin Tryon Avatar answered Oct 16 '22 01:10

Davin Tryon


Conditional compilation is all driven from compiler preprocessor definitions. This is the same approach used for the DEBUG constant, although Visual Studio hides the definition of that behind a checkbox. It's an efficient approach because when those symbols aren't defined then the methods aren't called at all; importantly the parameters being passed aren't evaluated either, so you can use relatively expensive checks in your code contracts without worrying about those checks slowing down release builds.

Microsoft's introduction to Code Contracts says this:

Most methods in the contract class are conditionally compiled; that is, the compiler emits calls to these methods only when you define a special symbol, CONTRACTS_FULL, by using the #define directive. CONTRACTS_FULL lets you write contracts in your code without using #ifdef directives; you can produce different builds, some with contracts, and some without.

Although this talks about using #define in the code to turn on code contracts:

#define CONTRACTS_FULL

as @NirMH said in the comments it's usually better to define it in the conditional compilation symbols for the project so you can have it on for some builds and off for others.

Conditional compilation settings

Note that CONTRACTS_FULL is the only option you have, although it's clearly been named to allow the possibility of more granular control in future.

like image 45
Matthew Strawbridge Avatar answered Oct 16 '22 01:10

Matthew Strawbridge