I think about starting to use Code Contracts in my code base.
I already use Code Analysis with all rules enabled and a goal of zero warnings.
However, when using Contract.Requires(parameter != null)
I get a warning from Code Analysis, namely CA1062:
CA1062 : Microsoft.Design : In externally visible method 'Foo', validate parameter 'parameter' before using it.
That's unfortunate, I don't want to disable that rule as I find it useful. But I also don't want to suppress every false occurrence of it.
Is there a solution?
As of Version 4.5.2 of the framework (possibly even 4.5) it is possible to tell Code Analysis about the contracts being enforced by Code Contracts. First create the following extension method and marker attribute
and now convert your entry null-tests to the following format:
The method name ContractedNotNull and the compilation switch RUNTIME_NULL_CHECKS can of course be changed to anything that suits your naming style.
Here is the original blog that informed me of this technique, which I have refined slightly; many thanks to Terje Sandstrom for publishing his research.
Rico Suter expands on this here by using additional attributes so that the debugger and inliner are smarter also:
To solve this problem, the following steps need to be performed:
Contract.Requires
.Step 1 gets rid of the CA warning, steps 2 to 4 enable a warning from Code Contracts that's at least equivalent.