Since I wasn't able to attend PDC last year, I'm still catching up on the sessions. I've watched almost all of them (starting w/ the native and parallelism stuff since that was the most applicable to me and working my way towards the rest of it.) Last night I watched the session on Code Contracts and Pex. I have to say that I'm REALLY impressed.

Code Contracts in .NET expose a bunch of great features for runtime checking and static analysis including:

  • Pre and Post condition checking
  • Object Invariants
  • Documentation generation
  • Testing conditions of the Result and OldValue (original value)
One of the beauties of code contracts is that they apply to derived classes. .NET 4.0 uses a code rewriter that acts on the intermediate language byte code to inject the contract checking (if runtime checking is turned on.) IDEs and consumers of your API can benefit from your contracts by utilizing your reference assemblies. You can turn off runtime checking when you ship your product so that you don't incur the performance penalty.

Where contracts leave off, Pex steps in. The purpose of Pex is to inspect your code and generate test cases for it. This can uncover errors (such as unhandled exceptions, integer overflows, etc) and act as a code coverage tool to make sure all of the paths in your code are correct. With the output of the inspection you can generate test projects that Pex can keep up to date. This seems like a great utility for coming up with and maintaining the simple, but important, types of unit tests that do bounds checking, look for unexpected inputs, etc.

I wish this stuff worked in native code! :)