- Original link: www.thomasclaudiushuber.com/2020/03/12/c-different-ways-to-check-for-null/
- Original author: Thomas
- Translation: The wolf at the end of the desert
What is the classic way to check whether a parameter value is null? If you have been developing in C for some time, 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 from C#7, you can use the is keyword to check null, as shown in the following code fragment:
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
But for C#7, there is even a shorter syntax. Discard has also been introduced. They are unused and ignored variables and are underlined (_) in the code. Combine the null merge operator (??), You can write a null check like this:
_ = name ?? throw new ArgumentNullException(nameof(name));
In other words, the whole 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 using the last method of discarding, but it may be too much for some developers. I think the is keyword is very clear and readable. It's my favorite.
is 关键字还有一个很大的优点,就是它忽略了任何==/!=运算符或者重载特定类。不管是否有操作符重载,它都将执行 null 检查。这比仅仅使用==更好。你可以在这篇博文中了解更多。
Is keyword and Not pattern in C#9.0
In C#9.0, if you want to check that an object is not null, then combining an is expression with the logical not pattern is very powerful. Before C#9.0, you had to use the following is expression to check whether an object is null:
if (!(name is null)) { }
Some developers tend to use 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. This is why many developers still prefer the classic approach:
if (name != null) { }
But starting from C#9.0, you can write the following non-null check, which I think is truly readable code:
if (name is not null) { }
summary
So, with C# 9.0, you can write your null / not-nulll checks like below, and I think that’s readable: So, with C#9.0, you can write a null/not-null check, as shown below, which I think is readable:
if (name is null) { }
if (name is not null) { }
Have fun programming!