Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out-of-the-box Code Contracts in .NET 4.0

I'd really like to try out the new Code Contract in Visual Studio 2010, but I don't want to install additional extensions to Visual Studio (since my code in shared with my coworkers). Now, when targeting .NET 4.0 I can use the new System.Diagnostics.Contracts namespace, but I don't get it to do anything yet.

For example, using

static void Main(string[] args)
{
    Greet(null);
    Console.ReadLine();
}

private static void Greet(string name)
{
    Contract.Requires(name != null);
    Console.Out.WriteLine("Hello {0}", name);
}

The program compiles and runs (displaying "Hello ") without warning of any kind. If I try to use Contract.Requires<ArgumentNullException>(name != null), I get a message telling me that I must use the rewriter, regardless of the value of name. Google tells me, that I can get any kind of magic when I install Code Contracts premium, but what is the purpose of this namespace when I don't? Can I use Code Contracts for something other than elaborate comments out of the box?

like image 917
Jens Avatar asked Feb 24 '23 07:02

Jens


2 Answers

Well, if you define the CONTRACTS_FULL preprocessor symbol then the various Contract.* methods will fail due to the rewriter not being run (as per comments). Unless you define the preprocessor symbol, they'll be ignored at compile-time.

The point of including the bare minimum Code Contracts classes in the framework is so that no extra software has to be installed when deploying the code - but you do need to install the extra tools in order to do the build-time post-processing.

like image 183
Jon Skeet Avatar answered Mar 05 '23 05:03

Jon Skeet


I guess the answer is in your objections to installing extensions. Having the contracts out of the box means that you can have all the use of the contracts you wish to an your coworkers will be able to compile the code without any extensions installed.

You can then go ahead and install the extension and get the real benefits from the contracts without imposing any new requirements on your coworkers

like image 41
Rune FS Avatar answered Mar 05 '23 06:03

Rune FS