C#: Different ways to Check for Null

What is the classic way to check if for example a parameter value is null? If you’ve developed with C# since a while, you might be familiar with this classic syntax:

public static int CountNumberOfSInName(string name)
{
  if (name == null)
  {
    throw new ArgumentNullException(nameof(name));
  }

  return name.Count(c => char.ToLower(c).Equals('s'));
}

Since C# version 7 you can use the is keyword for the null check like in the snippet below:

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

But with C# 7, there’s even a shorter syntax. Discards were also introduced. They are unused and ignored variables that are represented in your code with an underscore (_). In combination with the Null-coalescing operator (??) you can write the null check like this:

_ = name ?? throw new ArgumentNullException(nameof(name));

That means, the whole method looks just like this:

public static int CountNumberOfSInName(string name)
{
  _ = name ?? throw new ArgumentNullException(nameof(name));

  return name.Count(c => char.ToLower(c).Equals('s'));
}

To be honest, I really like the last approach using the discards, but maybe for some developers it’s too much. I think the is keyword is very clear and readable. It is my favorite.

The is keyword has also the big advantage that it ignores any ==/!= operator overloads on the specific class. It will do a null check, no matter if there’s an operator overload or not. That makes it better than just using ==.

Share this post

Comments (11)

Leave a Reply to Joel Cancel reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.