Besides syntactic sugar, Code Contracts is Microsoft's tool for the Design by Contract paradigm. http://en.wikipedia.org/wiki/Design_by_contract
Basically, this is a great way of thinking when you design your classes and operations. From experience, DbC works great with Test Driven Development, in which you basically define contracts and record tests for this before writing any business logic.
Behind the scenes, the contract contract generates code similar to your good old code at compile time, so the IL code contains all the checks.
For example, class
public class Scheduler { public bool ScheduleTask(string taskname, DateTime startTime, DateTime endTime) { Contract.Requires(!string.IsNullOrWhiteSpace(taskname)); Contract.Requires(startTime != null); Contract.Requires(endTime != null); return true; } }
The result is something like
public bool ScheduleTask(string taskname, DateTime startTime, DateTime endTime) { __ContractsRuntime.Requires(!string.IsNullOrWhiteSpace(taskname), null, "!string.IsNullOrWhiteSpace(taskname)"); __ContractsRuntime.Requires(true, null, "startTime != null"); __ContractsRuntime.Requires(true, null, "endTime != null"); return true; }
where _ContractsRuntime.Requests is as follows
internal static void Requires(bool condition, string msg, string conditionTxt) { if (!condition) { __ContractsRuntime.ReportFailure(ContractFailureKind.Precondition, msg, conditionTxt, null); } }
Hamid shahid
source share