A Shorter Way for Null Guard Clauses in C#

When we want to make sure that our method only accepts values that are not null, we can write guard clauses like these on top of the method:

string Combine(string address, string city, string zipCode)
{
    if(address == null)
    {
        throw new ArgumentNullException(nameof(address));
    }
    if(String.IsNullOrEmpty(city))
    {
        throw new ArgumentNullException(nameof(city));
    }
    if(String.IsNullOrWhiteSpace(zipCode))
    {
        throw new ArgumentNullException(nameof(zipCode));
    }

    // Do the work
    return $"{address} - {zipCode} {city}";
}

That works, but as you can see in this little example, this uses many more lines to check the data than it uses to do the work itself. Is there a better way to get this functionality?

Since .NET 6 we get ThrowIfNull() method on the ArgumentNullException class and .NET 7 brought us the other two methods we most often use in guard clauses:

1
2
3
4
5
6
7
8
9
string Combine(string address, string city, string zipCode)
{
    ArgumentNullException.ThrowIfNull(address);
    ArgumentNullException.ThrowIfNullOrEmpty(city);
    ArgumentNullException.ThrowIfNullOrWhiteSpace(zipCode);

    // Do the work
    return $"{address} - {zipCode} {city}";
}

With these new methods we can get the same functionality as before in half the lines of code. If the check is not matched, we get our ArgumentNullException and the name of the parameter that did not pass the check. This is one of the little improvements in .NET over the years that help a lot but get easily missed.