Stumbled across this question while researching code contracts for our codebase. The answers here are incomplete. Posting this for future reference.
How would I replace this with a code contract?
The code is fairly simple. Replace your runtime null check with this line. This will throw an exception of type System.Diagnostics.Contracts.ContractException
(which you apparently cannot catch explicitly, unless you catch all exceptions; it's not designed to be caught at runtime).
Contract.Requires(p != null);
I'm interested in finding out if a null has been passed in and have it caught by static checking.
You can use the Microsoft plugin for Code Contract static analysis, found here.
I'm interested in having a contract exception be thrown if null is passed in during our testing
Use the following, from above:
Contract.Requires(p != null);
Alternatively, if you want to throw a different exception (such as an ArgumentNullException
) you can do the following:
Contract.Requires<ArgumentNullException>(p != null, "Hey developer, p is null! That's a bug!");
This, however, requires the Code Contracts Binary Rewriter, which is included with the Code Contract plugin.
For production I want to exit out of the function.
From what I understand, building your project in Release mode will disable the Code Contract checking (although you can override this in your project properties). So yes, you can do this.
Can code contracts do this at all? Is this a good use for code contracts?
Short answer - Yes.