Published: 09 Sep 2009
By: Dino Esposito

In this article, Dino Esposito reviews code contracts in .NET using sample Visual Studio 2008 applications.

Contents [hide]

The Code Contracts Series

  • Code Contracts Preview: Preconditions  In this article, Dino Esposito reviews code contracts in .NET using sample Visual Studio 2008 applications.
  • Code Contracts Preview: PostConditions In this article, I'll focus on another aspects of Code Contracts - postconditions. Before going any further, though, let me briefly summarize some of the design choices the team made to expose the Code Contracts API.
  • Code Contracts Preview: Invariants In this article, I'll go through the concept and implementation of class invariants as supported by the .NET Framework 4 Code Contracts API.
  • Introduction

    Testability depends on a number of attributes of the software. One of these attributes is the ability to observe the current state of the software being tested and the output it produces. Another point is making it clear the initial conditions under which a piece of software should run, and what are expected results. If testers have a known and documented way to programmatically observe a given behavior, then they can easily test it against expected values and wrong values.

    A while back I wrote about class design and testability in a DotNetSlackers article that also introduced the concept of software contracts. Having a contract clearly defined for each class you write makes the code inherently more testable. Introduced by the Eiffel programming language about two decades ago, a software contract simply abstracts a few practical rules to use when writing classes. In brief, each method on a class is seen as the provider of a service. As such, it may require that callers fulfill some obligations. Abstractly speaking, a software contract is not much different from a “condition of service” document you are requested to agree when subscribing to many sorts of different contracts out there.

    A software contract is summarized by the following points:

    1. Awareness of the conditions necessary to for a method to execute.
    2. Awareness of the conditions verified after the method terminates.
    3. Awareness of the conditions which remain unchanged during the execution of the method.

    In the software contract jargon, these three points are also referred to as preconditions, postconditions, and invariants.

    Up until now, though, the concept of a software contract has remained a mere declaration of intent and any implementation was left to the good will of good developers. Something is changing though. In the .NET Framework 4, Microsoft is expected to ship a rich set of diagnostic programming tools that are nothing more than a possible implementation of a software contract as envisioned by Bertrand Meyer in the Eiffel programming language.

    .NET software contracts are known as code contracts. Not available in the Beta 1 of Visual Studio 2010, code contracts are available as a separate download and also for Visual Studio 2008. In this article, and in some future pieces, I’ll review code contracts using sample Visual Studio 2008 applications.


    To download Code Contracts, pay a visit to There is a forum for bugs, feedback, discussions, and questions on Code Contracts at Another way to get in touch with the team is to send feedback to

    Setting Up Code Contracts

    The setup program basically copies an assembly to the GAC and a few templates for the Visual Studio 2008 environment. Code contracts live in an assembly so you don’t have to resort to any special project template. Just create your Visual Studio project (console, Windows, WPF, ASP.NET) and add a reference to the new Microsoft.Contracts assembly. (Needless to say, this assembly will likely be renamed in the future as Beta 2 of the .NET Framework 4 ships. This article is based on a lab version of Code Contracts.)

    To make code contract classes visible, you need to add a diagnostic namespace, as below.

    Finally, you open the project properties page and select the newly added tab “Code Contracts”, as shown in Figure 1.

    Figure 1: The Code Contracts tab in the project properties dialog box.

    The Code Contracts tab in the project properties dialog box.

    To enable code contracts in your code, you should make sure that the checkbox “Perform Runtime Contract Checking” is checked.

    The syntax for code contracts is quite rich and variegated. In this article, though, I’ll mostly focus on preconditions. Let’s consider a sample class, as below.

    The class has two read/write properties. None of them can take just any value, however. Reasonably, you expect the ID to be a number greater than zero and the name to be non-null and non empty.

    How can you enforce these conditions?

    Cradling Over Validation and Runtime Checking

    The Customer class shown above is deliberately deceptive. It is, in fact, a class that symbolizes an entity in some object model. Classes that form the entity model of an application do require a validation layer to enforce business rules. You can, for example, decorate the same Customer class shown above with data annotations attributes:

    Data annotation attributes decorate properties expressing characteristics expected on the actual data being assigned to properties. For example, Required indicates that the property cannot be left null or empty. Likewise, StringLength sets the preferred length of the value; and so forth.

    What happens next when an instance of the Customer class is set through the code below?

    The code clearly violates one of the annotations on the Name property. However, nothing bad would happen at run time. Code around the class, however, may recognize a specific role to the annotations and produce effects on the user interface. In Silverlight, for example, data annotations are recognized and managed by the DataForm control. Sort of the same thing is expected to happen with ASP.NET MVC in the near future.

    In a way, data annotations express a contract; however, this contract cannot be automatically enforced at run time without some external code that takes care of it. On the other hand, the advantage of using attributes to express a contract is that you limit the impact on the code. Just for this reason, with attributes you are limited to express conditions using strings. Expressing conditions using free-form code gives an unparalleled level of flexibility.

    Data annotations are good for characterizing an entity model, where all that you may need is validating some content. Finding a proper text-based syntax and coming up with a validation layer is not a hard task. The Microsoft Enterprise Library, for example, does that very well.

    Software contracts have a wider scope than annotations and attributes. They easily apply to any method of any class and are expressed using plain code that executes at run time. Code contracts in the .NET Framework 4 offer just a simpler and standard syntax to express preconditions, postconditions, and invariants. Anything you can do with code contracts can also be done using plain code. It is mostly a time-saving feature that, however, also increases readability and eases maintenance.

    Preconditions in Action

    A precondition is a contract that regards the state of the method when it is invoked. Preconditions are generally are used for validating input parameters and for checking the state of the object. A precondition can be assimilated to an if statement that throws an exception if not verified. Here’s an example:

    The setter of the ID property throws if a value less than 1 is assigned. This is obviously a precondition. However, no special syntax makes it easy to recognize and perhaps modify in the code. A code contract provides just this. (And more.)

    Here’s how to rewrite the preceding code to use code contracts.

    If you assign the ID property a value of 0, then an exception is thrown, as in the figure below.

    Figure 2: A precondition failed.

    A precondition failed.

    The exception thrown is an internal exception defined by the Code Contracts framework—the ContractException type. This is only the behavior that takes place if no failure handlers are registered. If you want more done when a precondition is violated (i.e., you want to log a message), then you add a handler for the ContractFailed event.

    At the beginning of the application, you register the handler, as below:

    The event handler receives a bunch of information through the ContractFailedEventArgs class. In particular, it brings to your attention the type of the original exception (if any), the kind of failure (precondition or other), and the violated condition. (See Figure 3.)

    Figure 3: Handling failures in a custom way.

    Handling failures in a custom way.

    You can have multiple handlers registered. If the Handled property is set to true the framework stops there, otherwise it throws anyway ContractException.

    Preserving Legacy Code

    As mentioned, Code Contracts don’t offer more programming power than plain code. However, if you switch to Code Contracts you can benefit of some tools in the .NET Framework and Visual Studio 2010. If you’re already implementing preconditions in your code in the form below, you can easily turn that code to Code Contracts.

    Any if-then-throw sequence can be recognized as a code contract if it appears at the very beginning of the method and doesn’t have an else branch. If any Contract.XXX call follows the if-then-throw sequence, then recognition is automatic. Otherwise, you must place a sort of fictitious call to the Code Contract API to mark the end of the contract. A typical use looks like as below.


    Preconditions indicate the conditions to be established prior to calling a method. Preconditions can be expressed using plain code or the newest Code Contracts API. Using the Code Contracts API has the advantage of offering a common unified interface so that tools can extract information and build new facilities. In this article, I mostly focused on preconditions. However, Code Contracts goes far beyond preconditions as it is a full implementation of the concept of a software contracts. I’ll write more about Code Contracts in the future as detailed information is unveiled with the Beta 2 of the .NET Framework 4. For now, you can still play with a preliminary version of Code Contracts using Visual Studio 2008.

    <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Dino Esposito

    Dino Esposito is one of the world's authorities on Web technology and software architecture. Dino published an array of books, most of which are considered state-of-the-art in their respective areas. His most recent books are “Microsoft ® .NET: Architecting Applications for the Enterprise” and “...

    This author has published 54 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category

    Android for .NET Developers - Location and Maps
    In Windows Phone and iOS getting the current position of the device in terms of latitude and longitu...
    Android for .NET Developers - Using Web Views
    In this article, I'll show a native app that contains a web-based view. The great news is that HTML ...
    Android for .NET Developers - Building a Twitter Client
    In this article, I'll discuss the features and capabilities required by an Android application to ta...
    Developing a Hello World Java Application and Deploying it in Windows Azure - Part II
    In this article we will see the steps involved in deploying the WAR created in the first part of thi...
    Ref and Out (The Inside Story)
    Knowing the power of ref and out, a developer will certainly make full use of this feature of parame...

    You might also be interested in the following related blog posts

    Foxit PDF Previewer update read more
    Winforms Release History : Q2 2009 SP1 (version 2009.2.9.729) read more
    Thoughts on the Code Contracts Preview for .NET 4.0 read more
    ASP.NET MVC Source Refresh Preview read more
    Updated to MS Ajax RC read more


    Subject Author Date
    placeholder adoption of contract programming practices - Why so slow? David Allen 11/14/2009 6:55 AM

    Please login to rate or to leave a comment.