ArgumentNullException - how to simplify?

Update for C# 7

You can use a throw expression with the null coalescing operator. Here is an example from that page:

public string Name
{
    get => name;
    set => name = value ?? 
        throw new ArgumentNullException(paramName: nameof(value), message: "New name must not be null");
}

Original Answer

Personally, I use the ThrowIfNull extension method. I don't know who to credit but I definitely didn't invent it. It's nice because you can do assignment with the return value:

public static T ThrowIfNull<T>(this T argument, string argumentName)
{
    if (argument == null)
    {
        throw new ArgumentNullException(argumentName);
    }
    return argument;
}

Usage:

this.something = theArgument.ThrowIfNull("theArgument");
// or in C# 6
this.something = theArgument.ThrowIfNull(nameof(theArgument));

(Although some people think it's weird to call an extension method on a null instance)

If you really want to check more than one argument at a time, your example might be more streamlined if you used a params signature like so:

public static void CheckAndThrowArgNullEx(params object[] argsAndNames)
{
    for (int i = 0; i < argsAndNames.Length; i += 2)
    {
        if (argsAndNames[i] == null)
        {
            string argName = (string)argsAndNames[i + 1];
            throw new ArgumentNullException(argName);
        }
    }
}

and the usage would be:

CheckAndThrowArgNullEx(arg1, "arg1", arg2, "arg2");
// or in C# 6
CheckAndThrowArgNullEx(arg1, nameof(arg1), arg2, nameof(arg2));

On second thought, as KeithS mentions in the comments, it would probably be better to implement this as a set of overloads rather than using params object[] like this:

static void Check(object arg1, string arg1Name) { ... }
static void Check(object arg1, string arg1Name, object arg2, string arg2Name) { ... }
// and so on...

Try this: One line.

accounts = accounts ?? throw new ArgumentNullException(nameof(accounts));

Also, use nameof(), if the variable is ever renamed you will not have to hunt down all the "variable"s, let nameof() do that.


.NET 6 and beyond

There is a new method in .NET API ArgumentNullException.ThrowIfNull(someParameter).

This method is probably the best option which you can get.

C# 11 (currently as proposal)

Use new Bang Bang operator !! on a parameter to implicit check for null.

public string SomeFunction(Foo foo!!)
{
  // here, foo is already checked for null
  // ArgumentNullException(nameof(foo)) is thrown when foo = null
  return $"Here is {foo.Bar}";
}

TL;DR

The compiler will emit this code for every !! use

if (someArgument is null)
{
  throw new ArgumentNullException(nameof(someArgument));
}

Our SomeFunction will be transformed into

public string SomeFunction(Foo foo!!)
{
  if (foo is null)
  {
    throw new ArgumentNullException(nameof(foo));
  }
  return $"Here is {foo.Bar}";
}

There are several way to go about this.

Option A:

Break your functions into two - validation and implementation (you can see examples of this in Jon Skeet's EduLinq).

Option B:

Use code contracts that expect the parameters to be non-null.

Option C:

Using aspect oriented technologies such as code weaving to extract these checks out into an aspect. (as J Torres answered).

Option D:

Use Spec#, as CodeInChaos commented.

Option E:

???

Tags:

C#

Exception