I have recently started using the Microsoft CodeContracts on a large scale. These have been a fantastic addition to my toolset; because when I get the green flag on my code I know that I am pretty safe (it is beta, after all). I had to migrate quite a bit of code into the contracts and found that it can be quite a daunting task. A few things that I have picked up are:
- If you are migrating existing code and worrying only about contracts, switch off background checking. Firstly, this means that the results you get are comprehensive and secondly because of the build time you will think twice about hitting that build key again. Long builds == fewer builds == more time thinking == better code.
- Use code snippets. The ones provided by Microsoft are great! Think about creating your own or changing them. For example cren and cresn no longer throw ArgumentExceptions for me; they are both ArgumentNullExceptions. I also have snippets like create contract class for (cc – scaffolding for ContractClassFor) and contract class implementation (cci – ContractClass attributation).
- Invariants are your friend. Figure out what state a class should really be in and depend on that rather than Contract.Requires everywhere.
- A well placed Contract.Ensures will save you a lot of grief.
- Don’t loose hope. It may seem like it’s daunting at first – but as you start thinking in terms of contracts things become a lot faster. A single well-thought out Contract call will often clear off 5 warnings (for the bigger projects).
- Some classes can be skipped ([ContractVerification(false)]) – especially if they are internal. Don’t gung-ho and try and get everything in contracts; because sometimes they may be ill-suited for the task (and you would by ‘lying’ just to get the stuff to pass). These situations are few and far between; but they are there.
- New development = contracts. Full stop.
Overall I am finding fewer and fewer Contract failures during each build. This is mainly because CodeContracts is getting me into a better and more disciplined mindset. It’s a great tool and I highly recommend it.

Virtual Machine Installation Checklist
A quick checklist. Mostly just for me.