Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
Like this article? We recommend Installing the Code Contracts Library

Installing the Code Contracts Library

The code contracts library in the .NET Framework is contained in the System.Diagnostics.Contracts namespace. The class you will interact with the most is the Contract class that contains static methods which represent the code contract concepts of pre-conditions, post-conditions, and invariants.

Although the code contract classes are part of the .NET Framework, the additional tools that make them useful must be installed separately. These tools are available from the DevLabs Code Contracts web site. Currently, the following tools are provided:

  • Runtime Checking, which uses a binary rewriter to inject the contracts so they are checked at runtime.
  • Static Checking, which can determine contract violations without needing to execute the program. This not only checks for explicit contracts, but also implicit ones such as null dereferences and array boundary violations.
  • Documentation Generation, which adds new style sheets for Microsoft Sandcastle so that generated documentation contains contract information.

The code contracts tools are available in two editions:

  • Standard Edition, which can be used with any Visual Studio edition except the Express Edition, and includes the contract library, binary rewriter, reference assembly generator, and a set of reference assemblies for the .NET Framework.
  • Premium Edition, which can only be used with Visual Studio 2010 Premium or Ultimate Editions (or Visual Studio 2008 Team System), and includes all of the features from the Standard Edition plus the static checker.

Visual Studio Integration

When the code contracts tools are installed, C# and VB projects in Visual Studio have an additional property tab, shown in Figure 3, which allows you to configure the runtime and static checking tools, as well as some additional configuration options.

Figure 3 Project properties tab

Documenting Code Contracts

Although documenting your contracts in code is useful, it doesn't give other developers an easy way to see those contracts in the generated documentation. The code contracts tools enhance the XML documentation format to include elements that describe the contracts. This information can appear in the following locations:

  • In method elements (unless they are property get or set accessor methods or compiler-generated methods).
  • In type elements
  • In property elements, where two sub elements called getter and setter are used.

Because the code contracts tools automatically generate the additional XML elements used to describe the contracts, there is no need to manually add these elements.

  • + Share This
  • 🔖 Save To Your Account