The “Object reference not set to an instance of an object” is a very famous error in C# that appears when you get a NullReferenceException. This occurs when you try to access a property or method of an object that points to a null value. They can be fixed using Null conditional operators and handled using try-catch blocks.
In this post, we will learn more about the error and the ways to fix it.
What is “NullReferenceException: Object reference not set to an instance of an object” error?
As mentioned earlier, the NullReferenceException indicates that your code is trying to work with an object that has a null value as its reference. This means that the reference object has not been initialized.
This is a runtime exception that can be caught using a try-catch block.
Example code
try
{
string a = null;
a.ToString();
}
catch (NullReferenceException e)
{
//Code to do something with e
}
How to fix this error?
You can fix this error by using the following methods:
1) Using Null conditional operators
This method is easier than using an if-else condition to check whether the variable value is null. Look at this example,
int? length = customers?.Length; // this will return null if customers is null, instead of throwing the exception
2) Using the Null Coalescing operator
This operator looks like “??” and provides a default value to variables that have a null value. It is compatible with all nullable datatypes.
Example
int length = customers?.Length ?? 0; // 0 is provided by default if customers is null
3) Using nullable datatypes in C#
All reference types in C# can have a null value. But some data types such as int and Boolean cannot take null values unless they are explicitly defined. This is done by using Nullable data types.
For example,
static int Add(string roll_numbers)
{
return roll_numbers.Split(","); // This code might throw a NullReferenceException as roll_numbers variable can be null
}
Correct code
static int Add(string? roll_numbers) // As roll_numbers argument can now be null, the NullReferenceException can be avoided
{
return roll_numbers.Split(",");
}
The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!=null) to avoid this exception.