Skip to content

C# ‘is null’ vs ‘== null’

0118_description

Bing Image Creator — “black and white pattern on a small computer screen, on top of a wooden secretary”

When C# 7.0 was officially released in March 2017 it introduced several new features to make the life of developers easier, like tuples and deconstruction, local functions, expression body definitions and, the focus of this article, pattern matching.

One of the advantages of pattern matching is a more concise syntax for testing expressions and taking actions when there’s a match, increasing the readability and correctness of your code.

Checking for nulls is one of the most common usages. Before C# 7.0, if a developer wanted to check if a given value was null, usually the equality comparison would be used.

public static class PersonExtensions
{
public static string FullName(this Person person)
{
if (person == null) throw new ArgumentNullException(nameof(person));

return $"{person.GivenName} {person.Surname}";
}
}

With pattern matching, the extension method would be using the is operator and the null constant to check if the person variable is null.

public static class PersonExtensions
{
public static string FullName(this Person person)
{
if (person is null) throw new ArgumentNullException(nameof(person));

return $"{person.GivenName} {person.Surname}";
}
}

The change is so small that you are probably questioning if changing the way you code is really worthy for such a small readability improvement, to have the same results?

And you are right in thinking that way since that’s probably true for 99% of use cases (if not 99.999%) but what if you really want to be sure it works every time?

You see, reference types can overload the == operator and, if the developer decides to always return false when comparing to null, the first example would throw a NullReferenceException.

Let’s test that by overloading the == operator to always return false, whatever the parameters received:

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

zh_TWChinese