How to handle null values in C#

Null pointer exceptions are no fun. You can avoid them and keep your code clean and maintainable by using these techniques to elegantly handle null values in C#.

avoid detour side step trap hole in floor arrow by lucadp getty images
Lucadp / Getty Images

When working on applications in any programming language, you might have encountered null exceptions or null reference exceptions. A null pointer or a null reference is one that does not refer to a valid memory location or object. It is a problem that has plagued programmers as long as programmers have been writing programs.

A null value is a special value that denotes non-availability of a valid value. A null value is one that, when assigned to an object, resets the value of a field or a variable in the object to no value, i.e. an empty value. You must handle null values in your application’s code to avoid null reference exceptions and unexpected behavior of your application at runtime.

In this article, we’ll examine various ways to deal with null values in C#. To work with the code examples provided below, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Next.
  7. In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the Framework version you want to use.
  8. Click Create.

We’ll use this .NET 7 console application project to work with null values in the subsequent sections of this article. We’ll examine five ways to handle null values in C#. The one you should use will depend on the requirements of your application.

Null-conditional operator (?.) in C#

When an object is not null, you can access its members (data members and methods) using the null-conditional operator (?.). If the object is null, the null-conditional operator will return null but will not throw a runtime exception when accessing the members of the object. Consider the following class.

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; } 
    public string Address { get; set; }
}

Now write the following code to create an Author, assign values to the FirstName and LastName properties, and get the length of the Address property. Note that we have not assigned a value to the Address property, so it is set to null.

Author author = new Author();
author.FirstName = "Joydip";
author.LastName = "Kanjilal";
int length = author.Address.Length;

When the preceding code snippet is executed, you will encounter a runtime exception as shown in Figure 1 below.

nullreferenceexception 01 IDG

Figure 1. Oops, a null reference exception.

The following code example shows how you can use the null-conditional operator in C# to avoid the runtime exception.

Author author = new Author();
author.FirstName = "Joydip";
author.LastName = "Kanjilal";
author.Address = null;
int? length = author.Address?.Length;

Null-coalescing assignment operator (??=) in C#

In the event that the value of the left-hand operand is null, the null-coalescing operator (??=) will set the value of the right-hand operand of an expression to the operand present at the left-hand side. Here is an example of how this operator can be used in C#:

Author author = new Author();
author.FirstName = "Joydip";
author.LastName = "Kanjilal";
author.Address = null;
author.Address ??= "Default";
Console.WriteLine(author.Address);

Null-forgiving operator (!.) in C#

The null-forgiving or null-suppression operator (!.) allows you to suppress all warnings in an expression. You should use this operator only if you are sure that the value of a property or an object will not be null, and you want to suppress warnings in your application’s code that you know are incorrect.

The following code snippet illustrates how the null-forgiving operator can be used.

Author author = new Author();
author.FirstName = "Joydip";
author.LastName = "Kanjilal";
author.Address = null!;
int length = author.Address.Length;
Console.WriteLine(length);

Conditional operator (?:) in C#

You can use the conditional operator (?:) to evaluate an expression that includes a null value in one of the two operands. The conditional operator is also known as the ternary conditional operator, because the statements that use this operator have three parts: a condition (a Boolean expression), a consquent expression, and an alternative expression. The consequent expression (at the left-hand side of the :) is evaluated/returned if the condition evaluates true. The alternative expression (at the right-hand side of the :) is evaluated/returned if the condition evaluates false.

Here is an example that illustrates how the conditional operator can be used in an expression to handle null values:

Author author = new Author();
author.FirstName = "Joydip";
author.LastName = "Kanjilal";
author.Address = null!;
string result = (author.Address != null) ? author.Address : "Unknown";
Console.WriteLine(result); 

The is operator in C#

You can also use the is keyword to check if a value is null. This operator (is is a keyword and also works as an operator) can be used to compare constant values and even null values. The following code snippet shows how you can use this operator in C# to handle null values.

Author author = new Author();
author.FirstName = "Joydip";
author.LastName = "Kanjilal";
author.Address = null!;
if(author.Address != null)
{
    Console.WriteLine(author.Address);
}
else
{
    Console.WriteLine("The value of the Address property is null");
}

In addition to the five techniques shown in this article, you can check for null values by using the == operator in C#. The primary goal of using the operators demonstrated here to handle null values is to avoid having to write code to handle exceptions. You can keep your code clean and manageable using the techniques shown here.

Copyright © 2023 IDG Communications, Inc.

How to choose a low-code development platform