What’s New in C# 10: Simplify Argument Null Checking Code

This is part of a series on the new features introduced with C# 10.

Prior to C# 10 you may have had code similar to the following:

public static string Join(string a, string b)
{            
    if (a is null)
    {
        throw new ArgumentNullException(nameof(a));
    }

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

    return a + b;
}

If the parameters a or b are null then an ArgumentNullException will be thrown.

The nameof operator will create a string from the parameter name so the exception will contain information about what parameter was null.

One potential problem with this code is that it is easier to reference the incorrect parameter, for example:

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

The if statement is checking a but the nameof is referencing b.

C# 10 (.NET 6) introduces an improved way:

public static string Join(string a, string b)
{
    ArgumentNullException.ThrowIfNull(a);
    ArgumentNullException.ThrowIfNull(b);

    return a + b;
}

In the preceding code, a new static method called ThrowIfNull has been added on the ArgumentNullException class and allows us to quickly check and throw ArgumentNullExceptions.

Notice in this new version of the code we do not need to use the nameof operator, the parameter name will “magically” be worked out for us if an exception is thrown.

As an example, take the following code that passes a null to parameter a:

try
{
    SomeClass.Join(null, "bbbb");
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

If we run this we’ll get the following console output:

System.ArgumentNullException: Value cannot be null. (Parameter 'a')
   at System.ArgumentNullException.Throw(String paramName)
   at System.ArgumentNullException.ThrowIfNull(Object argument, String paramName)
   at ConsoleApp1.SomeClass.Join(String a, String b)

Notice the message contains a reference to the parameter named ‘a’ automatically.(Behind the scenes this is due to the new [CallerArgumentExpression] attribute – but you don’t need to know about the implementation details to make use of the ThrowIfNull method.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading