I answered a question on StackOverflow today that unfolded into a bit of a debate about the NullReferenceException and ArgumentNullException classes in the .NET Framework.
MSDN states that the NullReferenceException
…is thrown when there is an attempt to dereference a null object reference.
…is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
Konrad Rudolph (StackOverflow profile) made the point that we don’t need both types as if thrown they both logically mean that you are attempting to use a null reference, so ArgumentException is redundant. While I don’t think the documentation is completely clear (it could do with comparing each to the other to clear up any confusion), I disagree with Konrad’s assertion.
I believe that the NullReferenceException should be thrown when you are attempting to perform a dereferencing operation on a null reference, whereas the ArgumentNullException should be used when you are actively rejecting an argument because it is null. Konrad goes on to say that ultimately, the two operations are the same – i.e. “I’m trying to dereference this null reference therefore I need to throw an NRE” and “I want to dereference this null reference, so I need to throw an ANE as I cannot attempt to do this” – as they all come back to trying to dereference a null reference. However, I think Konrad is missing the difference in semantics between those two operations.
Konrad also suggests that the presence of both types is a bad decision in the design of the framework. Again, I disagree. There are actually 9 classes that inherit from ArgumentException that are there specifically to help us deal with invalid argument, i.e. the likes of ArgumentOutOfRangeException, InvalidEnumArgumentException et al.
Ultimately I expect it all comes down to a matter of taste. Personally I’d rather be told “Whoa, you can’t do that!
obj is null man, wtf?” than “Object reference not set to an instance of an object”, which – let’s face it – any seasoned .NET dev has seen enough of to last a lifetime.
What do you think?
Also, thanks to asawyer who was arguing from the same position as myself.