Main Article

The January-February 2010 CoDe Magazine article covers the Code Contracts Extensions in depth. If you don't have access to a printed copy of the magazine, you can refer to the quick reference below. The Internet version of the article should be fully available to non-subscribers by March 2010.

The current release also contains full examples that you can refer to.

Quick Reference

The Code Contracts Extensions project adds features to Microsoft's Code Contracts.

The Extensions mostly target runtime contract checking and not static contract checking. Many of the features were inspired by Microsoft's Enterprise Library Validation Application Block (validators, object validation and self validation).


The Condition class provides extension methods which take on the role of validators and centralize comparison logic.

Here are a few examples, used in Code Contract Requires clauses:
Contract.Requires(Contract.ForAll(positiveNumbers, (int number) => number.IsGreaterThan(0))); 
Contract.Requires(arrayIndex.IsInRange(0, 9));
Contract.Requires(Condition.IsInRange(arrayIndex, 0, 9));

Object Validation

The ContractValidation attribute can be applied to a class, interface of specific properties to provide object validation. An object is said to be in a valid state when all the contracts of the validable properties getters are satisfied.
The IsValid extension method is used in contract clauses to test an object state.

[ContractClass(typeof(ICustomerContract))] // (Properties contracts are defined in the ICustomerContract class - omitted for clarity)
public interface ICustomer
  int CustomerID { get; set; }
  string FirstName { get; set; }
  string LastName { get; set; }
  string Phone { get; set; }

// If all the properties's contracts are satisfied, then the following contract clause will also be satisfied:

Self Validation

As an alternative to object validation, a class can also provide self validation by applying the ContractValidation attribute to a property whose sole purpose is to specify the contracts that must be satisfied for the object to be considered valid.

private bool SelfValidates

    return true; 

// If the property's contract clauses are satisfied, then the following contract clause will also be satisfied:

Lazy Initialization & Lazy Contract Evaluation

The IInitializable interface can be implemented to support lazy contract evaluation in a lazy initalization scenario. That is, the real contract conditions are used only once an object is in an initialized state.
Please refer to the current release code sample for the full example.

string IAddress.CountryRegion
      // Laziness
      (this is IInitializable &&
       !((IInitializable)this).IsInitialized) ||
      // Contract
      (!Contract.Result<string>().IsNull() &&
         IsInRange(1, 50)));

    return default(string);
  // Setter skipped

Last edited Jan 11, 2010 at 7:45 PM by DevInstinct, version 3


No comments yet.