In my code i do this a lot:
myfunction (parameter p)
{
if(p == null)
return;
}
How would I replace this with a code contract?
I'm 开发者_如何学编程interested in finding out if a null has been passed in and have it caught by static checking.
I'm interested in having a contract exception be thrown if null is passed in during our testing
For production I want to exit out of the function.
Can code contracts do this at all? Is this a good use for code contracts?
The syntax for this is:
Contract.Requires(p != null);
This needs to be at the top of the method. All Contract.Requires
(and other contract statements) must precede all other statements in the method.
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.
These posts here and here have a lot of great options.
Edit: I misread your post the first time, thinking you were throwing an ArgumentNullException or something, until I saw Jon Skeet's comment. I would definitely suggest using at least one of the many approaches provided in the linked questions.
Reproducing one of the answers by John Feminella here:
[Pure]
public static double GetDistance(Point p1, Point p2)
{
CodeContract.RequiresAlways(p1 != null);
CodeContract.RequiresAlways(p2 != null);
// ...
}
精彩评论