views:

153

answers:

5

Is there a better way to require that an argument is not null in a method? I keep checking if any of the arguments that my method requires are null, as show below. But I'm wondering if there is a better way.

public void MyMethod(string a, int b)
{
   if(a==null){throw new ArgumentNullException("a");}
   if(b==null){throw new ArgumentNullException("b");}

   //more stuff here
}
A: 

There is no other better way. This is the way a ton of Microsoft libraries handle the situation.

You can always use an extension method to make it a little clearer.

static IsNullArgument(this Object o, string arg)
{
    if (o == null)
        throw ArgumentNullException(arg);
}
Daniel A. White
A: 

Google "Code Contract".

J.W.
+1  A: 

I personally like CuttingEdge.Conditions. It's easy to use, and makes this much more readable.

Reed Copsey
A: 

Rick Brewster (author of Paint.NET) blogged about a Fluent API alternative:

http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/

Martin Peck
A: 

This is one of the few areas where I think C# went backwards from C++.

In C++, you could write

void foo(Bar& bar) { /*...*/ }

to quite clearly indicate to both the compiler and other humans that foo took an actual instance of Bar. Yes, it is possible--with effort--to pass foo a null reference but that's not really legal C++.

Your only "solution" (of sorts) in C# is to make your classes structs instead, as value types in .NET can't be null (in your example, b can't ever be null because it is a System.Int32). The call to bar() will not compile:

 class A { }
 struct B { }

 static void foo(A a) { }
 static void bar(B b) { }

 static void Main(string[] args)
 {
  foo(null);
  bar(null);
 }

It certainly seems like it would have been nice for C# to have made it (much) more difficult to have null references; F#, for example, has no nullable types.

For some interesting commentary related to this matter, read Null References: The Billion Dollar Mistake (and the comments).

Dan