Code Contracts in C# and null checking

zachary picture zachary · Jan 14, 2011 · Viewed 8.5k times · Source

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?

Answer

Timwi picture Timwi · Jan 14, 2011

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.