Handling null values in C#

Handling null values in C#

Handling null values in C# and .NET comes with the territory. Null values were introduced by Tony Hoare in mid-1960s to represent missing or unknown data. This is a useful capability but it has resulted in null reference exceptions becoming one of the most common causes of bugs which developers face. As a result, Tony Hoare now calls the null reference the ‘billion dollar mistake’.

C# has always allowed reference types to be nullable, and as a result, the NullReferenceException is something .NET or .NET Core developers see frequently. In C# it is common to see code guarding against null references, often looking similar to the following.

if (variable != null) {
    // code to execute
}

Over the last few years C# has been adding more ways to handle null references. These new C# features help to improve the reliability of code and remove some of the clutter from guarding against null references.

Below are some of the ways you can protect against receiving a NullReferenceException in C# 9.0.

Using the is operator 

The is operator is a keyword in C# which is used for checking if a variable is compatible with a given type. When C# 7.0 was released, it added support for the constant pattern. This allows the is operator to compare values to a constant, such as null.

if (variable is null) {
    // code to execute
}

Using the is keyword to check for null values helps keep the code close to how it would be described in natural language. This can help to keep code easy to read and understand for developers.

Null-conditional operator

When C# 6.0 was released, the null-conditional operator was introduced into the language. This operator can be used to safely access members, ?., or an array index. ?[].

Person person = null;

if (person != null) {
    if (person.Address != null) {
        string city = person.Address.City;
    }
}

If any step in the chain is null the rest of the chain will not be executed and the chain will return null. This can help simplify your code by reducing the amount dedicated to guard conditions.

Person person = null;

string city = person?.Address?.City;

When there are nested properties the reduction of code can be substantial and make it much easier to read.

Null-coalescing operator

Prior to the null-coalescing operator being introduced, if you wanted to return an alternative value when a member was null, you would need to write a separate if statement.

Person person = null;

if (person?.Name is null) {
    return "Jane";
} else {
    return person.Name;
}

Today, you can open use the null-coalescing operator to simplify this and reduce the code you need to write to achieve the same result.

Person person = null;

return person?.Name ?? "Jane";

When the left-hand side of the operator is null, the result of right-hand operand will be executed and returned. If the left-hand operand is not null then the result of this will be returned.

Null-coalescing assignment operator 

The null-coalescing assignment operator was brought into the lives of C# developers with the release of C# 8.0. This operator allows code guarding against null values to be reduced to a few characters.

Person person = null;

if (person is null) {
    person = new Person();
}

This example can be simplified to the following example through the use of the null-coalescing assignment operator.

Person person = null;

person ??= new Person();

This reduces the clutter generally produced, and if it is commonly used reduces the risk of a null check being missed when it is required.

Summary

When developing .NET and ASP.NET applications, null values are a common occurrence and can easily bring the execution of your code to a rapid halt.

Today there are a number of ways to reduce the amount of code needed to handle null values in C#. These new options help keep code readable and easy to understand, while helping to improve its resilience.