Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

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:

Example: 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);
		}
	}
}
Try it

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:

Example: Prevent NullReferenceException by Checking NUll
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);
		}
	}
}
Try it

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:

Example: Prevent NullReferenceException using ?. operator
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; }
}
Try it

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:

Example: Prevent NullReferenceException using ??
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);
		}
	}
}
Try it

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.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.