How to avoid NullReferenceException in C#

Written by Cheng Yang

I have been working as a software developer for almost three years, the most common exception or bug I made is NullReferenceException -System.NullReferenceException: Object reference not set to an instance of an object. This exception is thrown when you try to access any properties / methods/ indexes on a type of object which points to null.

Common Scenario 1:

using System; 

public class Program
{
    public static void Main()
    {
          string dog = null;
	   var value = dog.ToString(); //Object reference not set to an instance of an object
   	   Console.WriteLine(value);
    }
}

In the example above, we try to call the ToString() method, it will throw a NullReferenceException because dog is pointing to null.

Common Scenario 2:

using System;

public class Dog
{
    public string Breed { get; set; }
    public int Age { get; set; }
}

public class Dogs
{
    public Dog Dog { get; set; }
}

public class Example
{
    public static void Main()
    {
        Dogs dog1 = new Dogs();
        int dogAge = dog1.Dog.Age; // Object reference not set to an instance of an object
	   
        Console.WriteLine(dogAge.ToString());  
    }
}

In the example above, you will get NullReferenceException because Dogs property is null, there is no way to get the data.

Solutions:

NullReferenceException can be very frustating during development, so how can we avoid NullReferenceException?

The solution is very simple, you have to check for every possible null exception property before accessing instance members.

Here are few useful methods:

Method 1 - use if statement

Check the property before accessing instance members.

If (dogs == null)
{
 // do something
}

Method 2 - use Null Conditional Operator(?)

It will check the property before accessing instance members.

int? dogAge = dog1?.Dog?.Age;

Method 3 - use GetValueOrDefault()

It will set a default value if the value is null.

int dogAge = Age.GetValueOrDefault();

Method 4 - use Null Coalescing Operator

You can set a custom value by using ?? if the value is null

var DefaultAge = 5;
int dogAge = dog1?.Dog?.Age ?? DefaultAge

Method 5 - use ?: operator

var DefaultAge = 5;
var IsDogAgeNull = dog1?.Dog?.Age == null;

int dogAge = IsDogAgeNull ?  DefaultAge : dog1?.Dog?.Age;

C# 8 brings a pretty neat feature - Nullable reference types to solve the NullReferenceException issue.

You will need to add the follow code into <PropertyGroup> in your .csproj

<LangVersion>8.0</LangVersion>
<NullableContextOptions>enable</NullableContextOptions>

and then you can do something like

Dog? dog = null; // nullable enable

I hope you found this post helpful, and let me know if you have another good way to handle the NullReferenceException.

Published March 11, 2020 by

undefined avatar
Cheng Yang Software Developer

Suggested Reading