• author: Nick Chapsas

How to Properly Check for Null in C

Null checks can be tricky in C#. C# is an old language and as features are added, they do not change any existing behavior, leading to feature overlapping and clashing with each other. In this article, we will discuss the proper ways to check for null in C#.

Default Way to Check for Null

The default way to check for null in C# is to use user is null. This is the correct way to perform null checks in modern C# programming, unless explicitly needed otherwise. If you scroll into Microsoft's code bases and other big code bases, you will find that this is how null checking is performed.

The Equals Operator

In C#, you also have the Equals() method to check if an object is null. However, if you try to use the Equals() method on a null object, you will get a null reference exception because this value is null. The reason why this is happening is that the Equals() operator can be overloaded.

Hardcasting Approach

The simplest way to check if the reference is equal or something else is by using ReferenceEquals(). Even if you have an overloaded Equals() operator, the ReferenceEquals() method will actually override the behavior.

if (ReferenceEquals(user, null))
    Console.WriteLine("user was null");

The is Not Null Version

With C# 9, a new way to perform null checks was introduced, which is the is not null version. This is the correct way to perform not null checks in modern C# programming. For example: if (user is not null) reads much better than if (user != null).

Using Pattern Matching

If we want to check that the full name of the child of the user is not null, we might try to write:

if (user.child.fullName is not null)
    // Do something

However, this is not the same as:

if (user is not null && user.child is not null && user.child.fullName is not null)
    // Do something

Pattern matching is trying to be defensive and add extra null checks, even though they are not extremely obvious. Hence, don't assume that the null checks work the same.


If you truly want to check if something is null or not null, use is null or is not null. Don't use the equals() operator as it can be dangerous. However, if the operators are part of your logic, including the null checks, then use them.

In conclusion, understanding the rules and everything covered in this article will make it easier for you to identify any issues and focus on using one of the two versions in your applications, unless explicitly needed otherwise.

Previous Post

Creating Clean Startup Code with SOLID and IConfiguration in .NET

Next Post

Retrieving Single or Multiple Resources in ASP.NET Core Web API

About The auther

New Posts

Popular Post