NullreferenceException in C#
The NullReferenceException is an exception that will be thrown while accessing a null object.
The following example shows the code that throws the NullReferenceException:
public class Program
{
public static void Main()
{
IList<string> cities = null;
DisplayCities(cities);
}
public static void DisplayCities(IList<string> cities)
{
foreach (var city in cities)
{
Console.WriteLine(city);
}
}
}In the above example, a NullReferenceException will be thrown in the DisplayCities() function while accessing cities list using a foreach loop because the cities list is null. If the caller of the DisplayCities() function pass a null IList value then it will raise a NullReferenceException.
Solutions to fix the NullReferenceException
To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them.
Solution 1: Check whether an object contains a null value or not using an if condition, as shown below:
public class Program
{
public static void Main()
{
IList<string> cities = null;
DisplayCities(cities);
}
public static void DisplayCities(IList<string> cities)
{
if (cities == null) //check null before accessing
{
Console.WriteLine("No Cities");
return;
}
foreach (var city in cities)
{
Console.WriteLine(city);
}
}
}In the above example, if(cities == null) checks whether the cities object is null or not. If it is null then display the appropriate message and return from the function.
Solution 2: In .NET 5, use the null conditional operator ?., as shown below:
public class Program
{
public static void Main()
{
Student std = null;
Display(std);
std = new Student(){ FirstName = "Vinod", LastName = "Dhar"};
Display(std);
}
public static void Display(Student std)
{
Console.WriteLine("Student Info:");
Console.WriteLine(std?.FirstName); //use ?. operator
Console.WriteLine(std?.LastName); // use ?. operator
}
}
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}In the above example, std?.FirstName is like if(std != null) std.FirstName. The std?.FirstName checks if std is not null then only access the FirstName property.
Solution 3: In .NET 4.x and above versions, use Null-Coalescing operator ?? to prevent an exception, as shown below:
public class Program
{
public static void Main()
{
IList<string> cities = null;
DisplayCities(cities);
}
public static void DisplayCities(IList<string> cities)
{
foreach (var city in cities?? new List<string>())
{
Console.WriteLine(city);
}
}
}In the above example, ?? is a null coalescing operator that checks if an object is null or not, if it is null then create an object. The cities ?? new List<string>() creates a new list object if a cities is null in foreach loop. Thus, the NullReferenceException will be not be raised.