Code Contracts were introduced in .NET 4.0 and they provide a language-agnostic method to express coding assumptions in programs.
They basically allow you to check for pre-conditions, post-conditions and other features and can greatly improve the testing process and the eventual quality of code that is being written.
From Microsoft:
Runtime Checking. Our binary rewriter modifies a program by injecting the contracts, which are checked as part of program> execution. Rewritten programs improve testability: each contract acts as an oracle, giving a test run a pass/fail indication. Automatic testing tools, such as Pex, take advantage of contracts to generate more meaningful unit tests by filtering out meaningless test arguments that don't satisfy the pre-conditions.
Static Checking. Our static checker can decide if there are any contract violations without even running the program! It checks for implicit contracts, such as null dereferences and array bounds, as well as the explicit contracts.
Documentation Generation. Our documentation generator augments existing XML doc files with contract information. There are also new style sheets that can be used with Sandcastle so that the generated documentation pages have contract sections.
Learn More:
- Code Contracts | Microsoft Research
- Code Contracts Overview Video and Tutorial by Greg Young | InfoQ
- Code Contracts | Microsoft DevLabs
- Tutorial on Using Code Contracts | jarloo.com