NullReferenceException in C# with Examples

  By : Suresh Dasari
  Posted On : 27-May-2023

Here we will learn what is nullreferenceexception in c#, how to handle/avoid/catch nullreferenceexception in c#, and how to fix nullreferenceexception in c# with examples.

What is NullReferenceException in C#?

In c#, NullReferenceException is an exception that will occur when we try to access a member (property, method, or field) of an object that is currently set to null or empty.

 

In application, when we get a NullReferenceExpcetion it indicates that we are trying to perform operations on a null object reference that could result a runtime error (System.NullReferenceException: 'Object reference not set to an instance of an object.') as shown below.

 

NullReferenceException Example in C#

Possible Ways to Get NullReferenceException in C#

Following are some possible ways of getting the NullReferenceException in c#.

 

Example1: When you try to access a null object reference, you will get a NullReferenceException error.

 

using System;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         string message = null;
         var result = message.Contains("Tutlane"); // NullReferenceException
         Console.WriteLine(result);
      }
   }
}

In this example, the message variable is assigned with a null value, and we are trying to check whether the message string contains the Tutlane text or not due to that we will get a NullReferenceException.

 

Example2: When you try to perform operations on a list object that contains a null value.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         List locations = null;
         locations.Add("Tutlane"); // NullReferenceException
         Console.WriteLine(locations);
      }
   }
}

In this example, we assigned a null value to the locations object without instantiating a reference type and trying to perform add operation due to that we will get a NullReferenceException.

 

Example3: When you forgot to dimension an array before performing any operations on it.

 

using System;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         int[] arr = null;
         arr[0] = 1; // NullReferenceException
         arr[1] = 2;
         arr[2] = 3;
         Console.WriteLine(arr);
      }
   }
}

In this example, we declared an integer array, but the number of elements that it can contain is never specified due to that we will get a NullReferenceException when we try to initialize values to it.

 

Example4: When a null object returned from the method, but you tried to perform operations on the returned value.

 

using System;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         var result = GetDetails();
         int i = result.Length; // NullReferenceException
         Console.WriteLine(i);
      }
      public static string GetDetails()
      {
         return null;
      }
   }

In this example, the GetDetails method returns null, and when you try to access the Length property of the returned value it will throw a NullReferenceException error.

 

Example5: When you pass null arguments to the methods, and you tried to perform operations on the argument values.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         List data = null;
         GetDetails(data);
      }
      public static void GetDetails(List names)
      {
         // NullReferenceException: Object reference not set to an instance of the object
         foreach (var name in names)
         {
            Console.WriteLine(name);
         }
      }
   }
}

In this example, the GetDetails() method is accepting the list of strings as an argument and looping through the list values to print the data. Here, when the argument value is null, the GetDetails() method will throw a NullReferenceException error.

How to Handle NullReferenceException in C#

In c#, we have many ways to handle or solve the “NullReferenceException” error.

 

Solution1: Before accessing the object elements, you need to ensure that the object parameters are not null. For that, you need to add null check or conditional statements to handle the null values as shown below.

 

using System;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         string message = null;
         if (message != null)
         {
            var result = message.Contains("Tutlane");
            Console.WriteLine("Data Exists:" + result);
         }
         else
         {
            Console.WriteLine("Message is Empty");
         }
      }
   }
}

In this example, we are checking whether the message variable is null or not before performing any operation on the message variable.

 

Following is another example of checking whether the list object contains null or not using the if condition.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         List data = null;
         GetDetails(data);
      }
      public static void GetDetails(List names)
      {
         if (names != null)
         {
            foreach (var name in names)
            {
               Console.WriteLine(name);
            }
         }
         else
         {
            Console.WriteLine("List is Empty");
         }
      }
   }
}

In this example, we are verifying whether the names argument in the GetDetails method is null or not before performing any operation on it.

 

Solution2: By using the null conditional operator (?) operator, we can prevent the NullReferenceException error. The null conditional operator (?) is useful to check the instance member before accessing the property.

 

using System;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         User user = null;
         GetDetails(user);
         Console.ReadLine();
      }
      public static void GetDetails(User user)
      {
         var name = user?.Name; // ? operator
         var location = user?.Location; // ? operator
         Console.WriteLine("Name:" + name);
         Console.WriteLine("Location" + location);
      }
   }
   public class User
   {
      public string Name { get; set; }
      public string Location { get; set; }
   }
}

In this example, we used the null conditional operator (?) to fetch the property values. Here, the user?.Location check if the user object is not null then only will access the Location property. The user?.Location will act like if(user != null) user.Location before accessing the property.

 

Solution3: By using the Null Coalescing operator (??), we can prevent the NullReferenceException error. The Null Coalescing operator (??) will help us to set the custom default value if the object is null.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         List users = null;
         GetDetails(users);
      }
      public static void GetDetails(List users)
      {
         var uInfo = users ?? new List(); // ?? operator
         foreach (var name in uInfo)
         {
            Console.WriteLine(name);
         }
      }
   }
   public class User
   {
      public string Name { get; set; }
      public string Location { get; set; }
   }
}

In this example, we used the Null Coalescing operator (??) with users object. The ?? operator will check whether the users object is null or not. If it is not null, it will use the same users object otherwise it will use the default value (new List<User>()).

 

Solution4: By using nullable types, we can also prevent the NullReferenceException error. If you define variables with nullable types like int? salary = null; it’s a shorthand version of Nullable<int> salary = null;. Here, the ? mark indicates that the salary variable can hold a null value and we can check whether the salary variable is null or not using if(salary.HasValue) or if(salary == null) before using the variable to prevent NullReferenceException error.

 

To avoid NullReferenceException errors at the project level, a new feature called nullable contexts has been introduced in the latest version of c#. The nullable contexts will help us to prevent NullReferenceException at the project level for that you need to add the <Nullable>enable</Nullable> property in .csproj file.

 

Before accessing the object elements or variable values, if we validate whether the object references or variables contain the value or not, we can easily prevent “NullReferenceException” errors in the applications.