What is NullReferenceException in C#?

In C# programming language, when we attempt to access a member (method, property, or field) of an object that is currently set to null, we will receive an exception called the NullReferenceException. This occurs because a null reference does not point to any memory address, so trying to access a null reference’s members throws an exception.

There are some of the few scenarios that demonstrate how the NullReferenceException can occur and how to manage it:

  • Accessing a property of a null object
  • Calling a method on a null object

Accessing a property of a null object

In this scenario, we will attempt to access a property of an object, and the object is currently initiated to null.

public class MyTestClass
{
public int MyTestProperty { get; set; }
}
public class Program
{
public static void Main()
{
MyTestClass myTestObj = null;
int value = myTestObj.MyTestProperty; // This line will throw a NullReferenceException
}
}

The MyTestClass class is created in the aforementioned code, and it has a property called MyTestProperty. The attempt to use the MyTestProperty property after initializing myTestObj to null will result in a NullReferenceException.

Before accessing an object’s members, we should check to see if it’s not null. We can handle the situation as in the example below:

public class Program
{
public static void Main()
{
MyTestClass myTestObj = null;
if (myTestObj != null)
{
int value = myTestObj.MyTestProperty;
// Do something with 'value'
}
else
{
// Handle the case when myTestObj is null
Console.WriteLine("myTestObj is null.");
}
}
}

Calling a method on a null object

Now, we will attempt to call a method on a null object.

using System;
public class MyTestClass
{
public void MyTestMethod()
{
Console.WriteLine("Hello World!");
}
}
public class Program
{
public static void Main()
{
MyTestClass myTestObj = null;
myTestObj.MyTestMethod(); // This line will throw a NullReferenceException
}
}

The coding example above uses a class called the MyTestClass and a method named the MyTestMethod. When we try to invoke the MyTestMethod method after setting myTestObj to null, a NullReferenceException is raised.

Before accessing an object’s members, we should again check to see if it’s not null. We can handle this situation as in the example below:

public class Program
{
public static void Main()
{
MyTestClass myTestObj = null;
if (myTestObj != null)
{
myTestObj.MyTestMethod();
}
else
{
// Handle the case when myTestObj is null
Console.WriteLine("myTestObj is null.");
}
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved