Search code examples
c#visual-studio-2010code-contracts

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?


Solution

  • 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.