Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the parameters in the constructors for ArgumentNullException and ArgumentException reversed?

Tags:

When designing software, I've always favoured consistency unless there is a really good reason to be inconsistent.

In the .NET Framework, we have the ArgumentNullException and ArgumentOutOfRangeException, which both derive from ArgumentException. All 3 of these have a constructor that accepts two string parameters - one for the paramName and one for the exception message.

Why do both of the derived classes reverse the parameter order?!

public ArgumentNullException(String paramName, String message)
    : base(message, paramName) { }

public ArgumentOutOfRangeException(String paramName, String message)
    : base(message, paramName) { }

Which means in my calling code, it'd look something like this:

public string DoSomething(string name, int age)
{
    if (name == null)
        throw new ArgumentNullException("name", "Name cannot be null.");

    if (name == string.Empty)
        throw new ArgumentException("Name cannot be an empty string.", "name");

    if (age < 18)
        throw new ArgumentOutOfRangeException("age", "Age must be at least 18.");

    //Do stuff
}

To me, this seems really illogical and often confuses me. Is there any reason at all for this design choice by Microsoft here? Are there any advantages to the reversed order when using these two derived exceptions?

like image 521
Connell Avatar asked Feb 13 '14 10:02

Connell


1 Answers

Because the constructor which takes only one argument, takes a different argument:

ArgumentNullException(String) takes paramName as argument, ArgumentException(String) takes a message.

This is actually very consistent this way. The two-string constructor just adds an argument, keeping the first one identical.

The reasoning behind it, is problably because ArgumentNullException doesn't need a message. The message is inherent in the exception type.

like image 189
Bart Friederichs Avatar answered Sep 24 '22 01:09

Bart Friederichs