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
}
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.
I personally like CuttingEdge.Conditions. It's easy to use, and makes this much more readable.
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/
You can write some utility methods. This is the common pattern in java.
user code:
implementation code:
You cannot get the variable name in the exception. but with the stack trace and your source code, it should be possible to easily track down.
This is one of the few areas where I think C# went backwards from C++.
In C++, you could write
to quite clearly indicate to both the compiler and other humans that
foo
took an actual instance ofBar
. Yes, it is possible--with effort--to passfoo
a null reference but that's not really legal C++.Your only "solution" (of sorts) in C# is to make your
class
esstruct
s instead, as value types in .NET can't benull
(in your example, b can't ever benull
because it is aSystem.Int32
). The call tobar()
will not compile: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).
Edit: A February 2013 footnote from Eric Lippert says "... it just so happened that when C# was first implemented it had always-nullable reference types, ... it seems plausible that
Nullable<T>
could have been implemented to work on any type, and reference types would then be non-nullable by default. We could have a type system whereNullable<string>
was the only legal way to represent "a string that can benull
". ... "