- Original link: https://www.thomasclaudiushuber.com/2020/03/12/c-different-ways-to-check-for-null/
- Original author: Thomas
- Translation: Desert End Wolf
What is the classic way to check if a parameter value is null? If you've been developing in C for a while, you may be familiar with the following 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'));
}
Starting with C# 7, you can use the is keyword for null checking, as shown in the following code snippet:
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
But for C# 7, there’s an even shorter syntax. Discards were also introduced. They are unused and ignored variables represented by an underscore (_) in code. Combining this with the null-coalescing operator (??), you can write a null check like this:
_ = name ?? throw new ArgumentNullException(nameof(name));
That means the entire method looks 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 discards, but it might be too much for some developers. I think the is keyword is very clear and readable. It's my favorite.
Another big advantage of the is keyword is that it ignores any == / != operators or overloads specific to a class. It will perform a null check regardless of whether there is an operator overload. This is better than simply using ==. You can learn more in this blog post.
C# 9.0: The is Keyword and the Not Pattern
In C# 9.0, if you want to check that an object is not null, combining the is expression with the logical not pattern is very powerful. Before C# 9.0, you had to use the is expression like this to check if an object was null:
if (!(name is null)) { }
Some developers preferred the following syntax to check that name is not null:
if (name is object) { }
But the above statement is neither readable nor easy to understand. That's why many developers still prefer the classic way:
if (name != null) { }
But starting with C# 9.0, you can write a non-null check like this, which I think is genuinely readable code:
if (name is not null) { }
Summary
So, with C# 9.0, you can write your null / not-null checks as shown below, and I think that’s readable:
if (name is null) { }
if (name is not null) { }
Happy coding!