Code Contracts are a new way to do both runtime and static checking of your code coming with .net 4.0/Visual Studio 2010.
Prerequisites
Visual Studio 2010 beta 2. To enable Code Contract project tab you need to update code contracts by downloading the latest version from Code Contracts web page. You’ll find very good introduction documentations on the same side from Documentation link (PDF).
Here is a really simple example of a code that uses Code Contracts
static void Main(string[] args) { decimal c = Divide(4, 0); // fails validation because b == 0 List<int> list = null; Add(list, 5); // fails validation list == 0 } static decimal Divide(decimal a, decimal b) { Contract.Requires(b != 0); return a / b; } static void Add(IList<int> list, int element) { Contract.Requires(list != null); Contract.Ensures(list.Count == Contract.OldValue(list.Count) + 1); list.Add(element); }
Pay attention to Contract static class and its Requires (pre-condition) and Ensures (post-condition) methods. There is lot more to these two methods i.e. you can even access original argument values through OldValue method – make sure you read the documentation.
Just the code by itself won’t do much. To enable both runtime and static checking you have to open project properties and check Perform Runtime Contract Checking and Perform Static Contract Checking checkboxes. If the static analysis has been checked then you’ll see warnings in the Error List (and Output) window regarding contracts failures. If you enable runtime checking you’ll get assertions (by default, but you can easily switch to exceptions) when the program execution hits contract checking failure.
The interesting aspect of Code Contracts is how it implements post conditions – it injects the proper code at the place of the post condition methods. Something like Post Sharp has been doing for years. Looks like AOP is slowly getting into the .net after all.
Try it for yourself.