NullReferenceException or ArgumentNullException
The API Design Guidelines encourage developers to check all their arguments and thereby avoid throwing a NullReferenceException. If an argument is null and the contract of the method forbids null arguments an ArgumentNullException should be thrown.
I get pushback on this periodically from developers that feel like the extra checks they are forced to implement are redundant. Consider the following code:
public void PrintValue(object o)
{
//Insert possibly deep callstackâ€
Console.WriteLine(o.ToString());
}
If you pass an instance that happens to be null nothing will blow-up or AV the process… you will simply get a NullReferenceException. That is way better than the equivalent thing in Win32, so what is the problem? The problem is developer productivity. If I have been up all night working on a program and I hit a NullReferenceException from 10 levels deep into Microsoft code I am likely to assume the bug is in the platform rather than my code (Occam's razor not withstanding). Now a few more hours later and maybe a call to PSS and I will realize my mistake, but I will certainly not be amazingly happy with the platform.
Suppose the author of the PrintValue() method followed our design guidelines
public void PrintValue(object o)
{
if (o == null) throw new ArgumentNullException();
//Insert possibly deep callstackâ€
Console.WriteLine(o.ToString());
}
Now, in the exact same circumstance I get an ArgumentNullException that specifically tells me I passed a null value where it was not expected. I immediately know the error is in my code and I can quickly find and fix my bug. Although I may not be able to attribute it to exactly this instance, I am overall much more happy and productive on the platform.
What do you think? Is this kind of error checking helpful in the .NET Framework and WinFX?