Elegant Invariant Checking with C# 3

Posted by Andrew on July 30, 2008

Of all the great advice in The Pragmatic Programmer, one of the ideas I’ve found most useful is that of Design by Contract. Most commonly, I check method preconditions using something like:

private void MyMethod(object arg1, string arg2)
{
  Invariant.ArgumentNotNull(arg1, "arg1"); // throws ArgumentNullException
  Invariant.ArgumentNotEmpty(arg2, "arg2"); // throws ArgumentOutOfRangeException
 
  // do stuff
}

I quite often check invariants at other points in a method too:

private void MyMethod(object arg1, string arg2)
{
  var myVar = AnotherMethod();
 
  Invariant.IsNotNull(myVar); // throws InvalidOperationException
 
  // do stuff with myVar
}

This approach works well but, in the case of preconditions, having to duplicate the argument name as a string is obviously not ideal. Perhaps using some of the new features of C# 3 we can do better?

Here’s one API I’ve been playing with:

private void MyMethod(object arg1, string arg2)
{
  Check.Argument(() => arg1.IsNotNull); // throws ArgumentNullException
  Check.Argument(() => arg2.IsNotEmpty); // throws ArgumentOutOfRangeException
 
  // do stuff
}

And for simple invariants:

private void MyMethod(object arg1, string arg2)
{
  var myVar = AnotherMethod();
 
  Check.Invariant(() => myVar.IsNotNull); // throws InvalidOperationException
 
  // do stuff with myVar
}

This approach leverages expression trees and extension methods to create a more fluent API and allows us to do away with the string argument when checking arguments.

Although I’m not 100% happy with it, I think I prefer this API. What do you think?

Download the code here.

kick it on DotNetKicks.com