C# – How Throwing ArgumentNullException Helps

cnull

Let's say I have a method:

public void DoSomething(ISomeInterface someObject)
{
    if(someObject == null) throw new ArgumentNullException("someObject");
    someObject.DoThisOrThat();
}

I've been trained to believe that throwing the ArgumentNullException is "correct" but an "Object reference not set to an instance of an object" error means I have a bug.

Why?

I know that if I was caching the reference to someObject and using it later, then it's better to check for nullity when passed in, and fail early. However, if I'm dereferencing it on the next line, why are we supposed to do the check? It's going to throw an exception one way or the other.

Edit:

It just occurred to me… does the fear of the dereferenced null come from a language like C++ that doesn't check for you (i.e. it just tries to execute some method at memory location zero + method offset)?

Best Answer

I suppose if you are immediately dereferencing the variable, you could debate either way, but I would still prefer the ArgumentNullException.
It is much more explicit about what is going on. The exception contains the name of the variable that was null, whereas a NullReferenceException does not. Particularly at the API level, an ArgumentNullException makes it clear that some caller did not honor the contract of a method, and the failure was not necessarily a random error or some deeper issue (though that may still be the case). You should fail early.

In addition, what are later maintainers more likely to do? Add the ArgumentNullException if they add code before the first dereference, or simply add the code and later on allow a NullReferenceException to be thrown?

Related Topic