I have been studying .NET 4.0 Code Contracts and looking on stackoverflow as well at question regarding this.
I still have never come across any sample code that use
One of the primary reasons to use CodeContracts is to enable Static Analysis to detect violations of the CodeContracts so they're caught early rather than resulting in bugs or unknown behavior at runtime.
You can disable runtime enforcement of CodeContracts if you want to.
Another good reason to use them is to add Contract definitions to XML Code Comments to enhance API documentation. This also works with Sandcastle though there are some tweaks necessary to integrate them fully. Refer to section 8.3 in the Code Contracts User Manual dated 2/4/2011 (or later) available at http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf
there is field of study on contracts: http://en.wikipedia.org/wiki/Design_by_contract it was long before they were introduced in .net.
Code contracts are useful to give answers to following questions:
If you can write small and readable contract for those questions then use it.
I use them anytime i need to validate that an input parameter needs to have a specific value (number is positive, object is not null).
For outputs, I use them anytime I am certain that a return value should be in a certain state (not null for example).
Having contracts in the code ensures that an exception will be thrown the moment that an unexpected value crops up, and not further down in the code where objects may accidentally be left in a corrupted state because of an accidental assumption.
Personally, I think it makes the code a lot cleaner. The notation makes it a lot less to write (instead of using if(....== null)....). This way too Contract.Requires
is very up front in what it is trying to accomplish. When I see that I know that the code is evaluating that a parameter is in a certain state.