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 : ///<summary> /// 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.Requires(cachedEntities.Keys.Contains(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 ...