ArgumentNullException / Don't forget the precedent!

At work this week, I discovered a quirk in the .NET API.

An ArgumentException is thrown when one of the arguments to a method is invalid. A more specific ArgumentException is an ArgumentNullException which (as you may have guessed) is thrown when an argument is invalid because it is null.

The funny thing is that while the base class provides this constructor -

public ArgumentException (string message, string paramName);

the one provided by the derived class is -

public ArgumentNullException (string paramName, string message);

The order of the parameters is swapped!

Inconsistencies like these can lead to confusion. In our case, we ended up with code that was passing arguments to the constructor in the wrong order -

throw new ArgumentNullException(messageArg, paramNameArg);

The moral

Always strive for consistent interfaces.

Breaking reasonable expectations by creating inconsistencies introduces accidental complexity. And for us mere mortals, accidental complexity is the enemy!


comments powered by Disqus