avatarJamie Burns

Summary

The web content discusses various methods for performing null checks in C#, emphasizing the evolution of these methods and recommending the use of 'is null' and 'is not null' introduced in C# 9 for their reliability and readability.

Abstract

The article "Checking for null in C# in 2022" explores the different ways to check for null values in C#, highlighting the progression from the traditional '== null' and '!= null' checks to the more modern 'is null' and 'is not null' introduced in C# 7 and C# 9, respectively. It explains the potential pitfalls of relying on the '==' and '!=' operators, which can be overridden by custom class implementations, leading to unpredictable behavior. The author advocates for the use of 'is null' and 'is not null' as they provide consistent behavior regardless of class-specific operator overrides and are more intuitive to read, thus reducing the likelihood of errors. The article concludes by recommending the latest C# 9 syntax for null checks as the best practice moving forward.

Opinions

  • The traditional '== null' and '!= null' checks are considered less reliable due to the possibility of operator overrides causing unexpected behavior.
  • The 'is null' and 'is not null' checks are preferred for their clarity and consistency, as they are not affected by class-specific implementations.
  • Pattern matching with 'item is { }' is acknowledged as a feature that has grown in popularity but is seen as less readable for simple null checks compared to the dedicated 'is null' and 'is not null' syntax.
  • The author suggests that the 'is null' and 'is not null' checks are the most readable and reliable methods for null checking in C# 9 and beyond.
  • There is an anticipation that C# will continue to evolve, and the author expresses a commitment to updating the community on best practices for null checks as the language develops.

Checking for null in C# in 2022

Let’s look at the different ways we can check for null, and see which way is best

Photo by Kier In Sight on Unsplash

Null checks are things that all developers have to deal with at some point.

Fortunately this is really easy to do in C#, so it’s very simple to get your head around.

Unfortunately, as the C# language has developed over the last few years, there are now a whole range of ways to check for null. Most ways are essentially the same (they just look different), however there are a couple of caveats you need to be aware of.

So we’ll go through all these options here, so you can see what’s going on.

Option 1: item == null

Here we’re using a double-equals (‘==’) to check the object against the null keyword.

This is the original null check in C#, and is the only option you’ve got if you’ve not upgraded beyond C# 6.

It’s a solid option — it’s been around for years, it’s clear what’s going on, and everyone knows what it’s doing.

However, there is a drawback, which has prompted the language to evolve the other null checks that are listed below.

This check relies on the ‘==’ operator, which is defined by the object. Now, 99% of the time, this will work exactly as you’d expect. However, it’s entirely possible for the behaviour of this operator to be changed for this class, and that’s when things can get a little unpredictable.

Using a class with the default behaviour of ‘==’, everything works as you would expect:

However, say you’re using a class that has overridden the implementation of ‘==’ and ‘!=’ . The result of that ‘==’ check is now dependent on the class’s custom implementation, which may or may not be what you expect:

All of a sudden, when you use ‘==’ for a null check, you’re using this custom logic instead of the basic check you’re after. It’s very unlikely a class will implement ‘==’ and ‘!=’ like this, however it’s possible there may be some complex logic in there to compare the contents of the two objects, and you’re assuming the null checks are handled correctly. You’re not really interested in this complex logic, you just want to know if it’s null.

Note that the same principles apply when you want to check if something is not null. Instead of using ‘==’ you can use ‘!=’:

This however has the same problems as ‘==’, since the definition of ‘!=’ can be overridden too.

This leads us onto option number 2:

Option 2: item is null

Here, instead of using ‘==’ we’re using the ‘is’ keyword. You’ll be familiar with using ‘is’ if you’ve worked with type checking or generics, because it’s the same keywork to check if an instance of an object is of a specific type.

We can use this here to check if the object ‘is’ null:

Again, this makes it very clear what’s going on, and is very readable. This form was introduced in C# 7, so it has been around a while, and should be pretty common-place now.

It’s good, because the behaviour cannot be changed by the class itself — so even if the class has overridden the ‘==’ and ‘!=’ operators, the ‘is’ check will still behave in the same way.

The slight drawback of using this approach is when you want to check that something is not null. You have to negate the check:

It functionally works, but I’m sure you’ll agree with me that it’s not great for readability.

Option 3: item is { }

You can also use pattern matching to check for nulls:

This kind of pattern matching was also introduced in C# 7, but has grown in popularity as the language has expanded on how pattern matching can be used.

Pattern matching itself is awesome (and mainly out of scope of this article), and allows you to easily do complex checks that otherwise would have required multiple lines of code to do the same thing. And, in the basic form, it can be used for checking for null.

However, for such a simple check, it’s arguably the least readable option we’ve listed here. For those familiar with pattern matching, seeing ‘{ }’ makes perfect sense. For everyone else, that may require a bit of head-scratching, and an optimistic/hopeful internet search to see what’s going on with it.

Option 4: item is not null

Introduced in C# 9, we can now use the ‘not’ keyword alongside ‘is’, to check that a variable is not null:

It works exactly how it looks — it checks that the variable is not null. It’s completely clear what it’s doing, and works without any caveats.

Summary

As you can see, in C#, we’ve got different options for checking for null.

The classic ‘==’ and ‘!=’ should ideally be avoided for null checking, because of the very slim chance that the operators have been overridden, and could result in some unexpected results.

If you’re able to use C# 9 and beyond, your best bet is to use ‘is null’ and ‘is not null’. They are the most readable null checks available and they work 100% of the time.

Time will tell if this will change as C# is developed even further, in which case, I’ll try my best to update this article as, and when, that happens!

Programming
Csharp
Null
Patterns
Coding
Recommended from ReadMedium