In .NET most of us have faced the “Object reference not set to an instance of an object.” error. Today in this article we will discuss this error and when this error occurs in the code. We will also share some debugging tips for solving this error.
Null Reference Exception
Null Reference Exception is one of the most common runtime errors that is produced when the code non-nullable variable is null.
For instance
MyClass obj = null;
Console.WriteLine(obj.SomeProperty); // Throws NullReferenceException
In the example, we have initialized a class with a null value. In the next line, we are trying to access the property of MyClass but the issue is I haven’t initialized the class with the new MyClass() thus it will throw a runtime error.
List names = null;
Console.WriteLine(names.Count); // Throws NullReferenceException
This will also trigger the null exception c# error as I have not initialized the list and I am trying to access the list count.
int[] numbers = null;
int firstNumber = numbers[0]; // Throws NullReferenceException
// Solution
if (numbers != null && numbers.Length > 0)
int firstNumber = numbers[0];
The above example is also similar to our previous case as we have initialized the list and are trying to access the zero index of the list. However, we can fix this issue with a conditional statement (if) that will check if the list is null or has zero length then it will not look for the value at the 0 index.
int? nullableInt = null;
int value = nullableInt.Value; // Throws NullReferenceException
// Solution
if (nullableInt.HasValue)
int value = nullableInt.Value;
Here we have created a nullable integer and then after it, we are trying to access the value, in good case, it might execute successfully but when we have the worst case then the code will break very easily. A proper solution to the problem could be using HasValue which will return a bool if it has value then it will return true else false.
Solution For Object Reference Not Set
For Null Exception c#, there is no such solution that can resolve all the null issues however you can use try and catch to at least keep your code safe from breaking and also use it to log the breaking point in your code.
However, can we use null safety ?? it will help us to keep our code unbreakable to the nullable exception but we can only use them when we have a default value.
int productId = getProduct.id ?? 0;
In the above example, I’m trying to access the getProduct.id, if the value is null then it will be 0, but is it good for all cases? The answer is not because if we are fetching results from our database and when the ID is invalid then the code should immediately return an error as “Product ID is Invalid” rather than return the product with 0 ID (if it exists in the database).
This solution is useful when you can prevent return null, for instance, I have an e-commerce website and I have a product with a null in the quality and when I want to show it on the front then it must show 0 rather than null, it is some of the common use cases for it.
A real-life example
John goes grocery shopping without checking for his wallet. When he arrived he put some groceries in his cart, then he went for billing. At that time he checks his wallet then he knows that his wallet is missing, this moment is similar to our null exception c# case as John was expecting his wallet but now it is missing.
We can handle this null exception c# using the condition that John can return if his wallet is missing or call his family member to bring him his wallet, however, he can also check his wallet before leaving.
In this case, John can also have some null safety as he keeps a 100 dollar in his pocket in case his wallet is missing he can give that 100$ dollar for billing.
In conclusion, Object reference not set to an instance of an object can be useful for preparing for a solution as you can make your code foolproof against worst cases.
To learn more about the Null Reference Exception C# you can visit here Microsoft. If you want to read more topics on .Net you can visit our category page Net.