C# NullReferenceException

Summary: in this tutorial, you’ll learn about C# NullReferenceException, understand the causes, and how to avoid them.

A NullReferenceException is a runtime error that occurs when you try to access a member of an object that is null.

Understanding null

When you declare a variable of a reference type, C# stores the actual data on the heap and the reference that refer to the actual data on the stack. For example:

using static System.Console;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public override string ToString() => Name;
}

public class Program
{
    public static void Main(string[] args)
    {
        var person = new Person { Name = "John Doe", Age = 25 };
        WriteLine(person);
    }
}Code language: C# (cs)

In this example, we define a Person class with two properties Name and Age, and create a new Person object. The person variable is an instance of the Person reference type.

Behind the scenes, C# stores the person variable on the stack and the actual object on the heap as illustrated in the following picture:

C# NullReferenceException

When you declare a variable with the Person type but do not initialize it, the person reference doesn’t refer to anything, which is also known as null:

Person person; // nullCode language: C# (cs)

C# NullReferenceException exception

The NullReferenceException is a runtime error that occurs when you assign null to a variable and then attempt to access its properties and methods.

The following example shows how to declare a variable, assign null to it, and attempt to access its property:

using static System.Console;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public override string ToString() => Name;
}

public class Program
{
    public static void Main(string[] args)
    {
        Person person = null;
        WriteLine(person.Name); 
    }
}Code language: C# (cs)

The program causes a NullReferenceException exception because the person variable is null.

To avoid it, you need to initialize the person object properly before accessing its property. For example:

Person person = new Person { Name="John Doe", Age=25 };
WriteLine(person.Name);Code language: C# (cs)

This example is trivial and can be easily avoided in practice.

Typically, a NullReferenceException occurs when you assign the result of a method, which can return either a Person object or null, to a variable.

If the method returns null and you attempt to access the property of the Person object, you will encounter a NullReferenceException. For example:

using static System.Console;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set;}
    public override string ToString() => Name;
}

public class Program
{
    static Person CreatePerson(string name, int age)
    {
        if (age <= 0 || string.IsNullOrEmpty(name))
        {
            return null;
        }
        return new Person { Name = name, Age = age };
    }

    public static void Main(string[] args)
    {
        var person = CreatePerson("Jane", 0);
        WriteLine(person.Name);
    }
}Code language: C# (cs)

In this example, the createPerson() method returns null if the age is less than or equal to zero or the name is empty.

In the Main() method of the Program class, we declare a person variable and initialize it to the return value of the CreatePerson() method.

Because the age is zero, the CreatePerson() method returns null. Accessing the Name property of the person object will cause a NullReferenceException.

To avoid this, you can check if the person is null or not before accessing its properties and methods like this:

var person = CreatePerson("Jane", 0);
if (person != null)
{
    WriteLine(person.Name);
}Code language: C# (cs)

To make it shorter, you can use the null conditional operator ?. that immediately returns null if the expression on its left-hand side evaluates to null. For example:

var person = CreatePerson("Jane", 0);
WriteLine(person?.Name);Code language: C# (cs)

By using the null conditional operator, you don’t need to use the if statement, resulting in a more concise code.

The Person object has the property Name with a string reference type. If you don’t initialize the Name property and attempt to access its method like ToUpper(), you also get a NullReferenceException. For example:

using static System.Console;

public class Person
{
    public string Name {  get; set; }
    public int Age { get; set;}
    public override string ToString() => Name;
}

public class Program
{
    public static void Main(string[] args)
    {
        var person = new Person { Age = 25 };
        WriteLine(person.Name.ToUpper()); // NullReferenceException
    }
}Code language: C# (cs)

To avoid this, you can use the null conditional operator (?.). For example:

using static System.Console;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public override string ToString() => Name;
}

public class Program
{
    public static void Main(string[] args)
    {
        var person = new Person { Age = 25 };
        WriteLine(person?.Name?.ToUpper()); 
    }
}Code language: C# (cs)

Summary

  • A NullReferenceException occurs when you attempt to access a member of an object that is null.
  • Always check if an object is not null before accessing its properties and methods using an if statement or null conditional operator (?.)
Was this tutorial helpful ?