Code Contracts

A few days ago I discovered Code Contracts. It is a tool and a framework that enables us to define constraints on parameters and return values.
For example, here is a simple code :
/// Dummy base class
/// </summary>
public class Entity

/// <summary>
/// Simple cache
/// </summary>
static class Cache
private static Dictionary<int,Entity> cachedEntities = new Dictionary<int,Entity>();

public static Entity GetCachedEntity(int entityId)
Contract.Ensures(Contract.Result<Entity>() != null);

return cachedEntities[entityId];

// ...

Notice the use of the Contract class (in the System.Diagnostics.Contracts namespace of the Microsoft.Code Contracts assembly). This class contains methods that we can use to define input constraints (Requires) and output constraints (Ensures).
The Code Contracts framework can perform a static analysis at compile time, and verify if the callers satisfy the requirements. It can also inject code into the method to enable dynamic constraint checking. If a constraint is not satisfied, a ContractException will be thrown at runtime.
This is configurable from the properties of the project in Visual Studio (for example).

Popular posts from this blog

Handling exceptions the right way in WCF (part 2)

Adding a delay before processing Textbox events

Change the deployment URL of a ClickOnce application