Getting Code Contracts to Work in Visual Studio 2010 RC

Microsoft released Visual Studio 2010 RC to the public on Wednesday along with .NET Framework 4.  One of the new framework features is Code Contracts.

Contracts, like assertions, express assumptions in your code by testing conditions.  For example, the following code requires someParameter to have a value greater than zero or a failure message is displayed:

using System;
using System.Diagnostics.Contracts;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DoSomething(0);
            Console.ReadLine();
        }

        static void DoSomething(int someParameter)
        {
            Contract.Requires(someParameter > 0, "someParameter must be greater than zero.");
            Console.WriteLine("Success");
        }
    }
}

Code Contracts surpass assertions with their ability to do static checking.  They can detect contract violations during a build without even running your code.  They’re also tailored for specifying method-boundary contracts (preconditions and postconditions) while assertions are not.

I assumed contracts would work out of the box, but unfortunately that’s not the case.  .NET 4 does include the System.Diagnostics.Contracts namespace and allows you to write contract-based code, but it won’t do anything unless you install Code Contracts separately.

Download Code Contracts from Microsoft DevLabs

After the install you’ll see a new tab in your project properties called “Code Contracts”.  There you can specify Runtime Checking, Static Checking or both.

Enabling contract checking
Enabling contract checking

Note that static checking is only available in the Premium Edition, which will only install if you have VS 2010 Premium or Ultimate.  The barrier to entry here is too high, in my opinion.  Have a look now before the release candidate expires and these features are out of reach to the average developer.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s