Stumbled upon this question while researching code contracts for our code base. The answer here is incomplete. Publish this for future reference.
How can I replace this with a code contract?
The code is pretty simple. Replace the zero execution check on this line. This will throw an exception of type System.Diagnostics.Contracts.ContractException (which you apparently cannot catch explicitly, unless you catch all the exceptions, it is not intended to be detected at runtime).
Contract.Requires(p != null);
I am interested to know if the pool passed and caught a static check.
You can use the Microsoft plugin for static analysis of Code Contract, found here .
I am interested in excluding a contract exception if null was sent during our testing
Use the following, above:
Contract.Requires(p != null);
Alternatively, if you want to throw another exception (e.g. ArgumentNullException ), you can do the following:
Contract.Requires<ArgumentNullException>(p != null, "Hey developer, p is null! That a bug!");
However, this requires a binary rewriting of Code Contracts code, which is included in the Code Contract plugin.
For production, I want to exit the function.
From what I understand, creating your project in Release mode will disable the verification of the contract code (although you can override this in your project properties). So yes, you can do it.
Can code contracts do this at all? Is this a good option for code contracts?
The short answer is yes.