Code Contracts

Posted on December 3 by bjn

Code Contracts is shipped with .NET Framework 4.0 in the namespace System.Diagnostics.Contracts. Code Contracts is a way to do runtime and static checking of pre and post conditions in the code. Like Debug.Assert on steroids. The biggest thumbs up is the static analysis which would generate compile errors if the condition is false. Sounded like an awesome thing so after creating a new project in VS2010 with target 4.0 I wrote the following method.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Divide(10,0));
        }

        public static double Divide(int numerator, int denominator)
        { 
            Contract.Requires(denominator != 0);
            return numerator / denominator;
        }
    }

Compiled the program with no compile errors. Weird. Executed the program and thought I’d at least would get a runtime exception of some sort that the condition failed. Wrong again, no runtime exception. Well, only an ordinary DivideByZeroException was thrown. After inspecting the code with Reflector I could see that the Contract.Requires line had been removed by the compiler.

Googling a bit and I came to this page. OK, so even if Code Contracts are shipped with .NET FrameworPhoto by Céline Mackowiakk 4.0 the tools are not included and the code (Contract.Requires) will be removed by the compiler by default. The page told me to download the tools from devlabs.

While at that page I realized that the static checking of contracts is only available to PREMIUM and ULTIMATE versions of VS2010. That’s really bad. I totally agree with https://connect.microsoft.com/VisualStudio/feedback/details/481327/make-data-contract-static-checking-available-in-professional-edition?wa=wsignin1.0 and http://connect.microsoft.com/VisualStudio/feedback/details/106484/code-quality-tools-should-not-be-limited-to-team-system.

Anyways, to at least get runtime validation running with VS2010 Pro I had to:

1. Download the STANDARD edition of Code Contract tools from this page.

2. Go to to project properties and check the checkbox Perform runtime checking, which is found on the tab Code Contracts.

After that I got the runtime exception ContractException: precondition failed.

Lesson learned, there’s a price for code quality, it just happens to be the same price as for VS2010 Premium or Ultimate…


blog comments powered by Disqus