Friday, April 29, 2011

Is there a way to require that an argument provided to a method is not null?

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
}
From stackoverflow
  • 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);
    }
    
  • Google "Code Contract".

  • 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/

  • 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).

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.