Updated April 15, 2023
Introduction of C# NullReferenceException
The NullReferenceException is an exception that is thrown by the program when we attempt to access any type of member which has value as null, meaning when we try to access a variable that holds no value or a null value, Null Reference exception will be thrown. This exception is applied for various releases of .NET, .NET Core, and .Net Framework. These reference variables in C# are quite matching with the concepts pf pointers in C. There are various situations when the NullReferenceException occurs and there are multiple ways to avoid or solve it.
Syntax:
Follow is the standard syntax used for the implementation of the NullReferenceException:
public class NullReferenceException :SystemException
The Null Reference Exception is inherited from System Exceptions which basically can be found within Object and into Exception. As we know this is one of the most common exception and there are various ways to handle it.
How NullReferenceException Works in C#?
To simply understand, a Null Reference Exception is a result of an event where we try to access a variable that is not referencing any other object. Now, referring to a reference isn’t a problem here, but when a reference variable is not referencing any other object, then it is basically treated as null. This is where the problem arises when the code is referenced to a point which ends up into a null, then we are encountered with an exception, named NullReferenceException. There can be various scenarios where a Null Reference Exception is thrown by the program. When we execute a program and if it encounters the null reference exception, the output will be something like this:
Unhandled Exception:
System.NullReferenceException: Object reference not set to the instance of the object.
Examples
Now that we have understood what the exception is about and how it works, let us move to properly demonstrating the exception with examples. For our first example, which is very simple, we have a simple variable that holds null value and then we will attempt to work do that variable, but being a null, it will throw the Null Reference Exception. The code for the program is as follows:
Code:
using System;
public class SampleProgram {
public static void Main() {
string name = null;
varval =name.ToString();
Console.WriteLine(val);
}
}
Code Explanation: Stated with using System, we have our class Sample which is public. Then we have our static void main statement, followed by the creation of a simple string variable named name and value assigned is null, meaning no value to the variable. This string variable is important here, later we create another variable named val, where we attempt to convert the value of name into a string. Finally, we have out a print statement that will print the value of name, which is now converted using ToString(). Refer the below attached screenshot for output:
Output:
If executed properly, the code will throw an error, which will be NullReferenceException. And the reason will be that when we are trying to call the ToString() method, it will go to the variable name, but our variable name has no value, meaning null. And as we know, the null value can’t be converted using ToString(). So our code will only print an error, which means code is running as expected.
As explained the program has been terminated by an exception. Moving on, we will demonstrate another simple example, which as explained lead to the same exception.
Code:
using System;
class SampleProgram {
static void Main() {
string val = null;
if (val.Length == 0) {
Console.WriteLine(val);
}
}
}
Code Explanation: Similar to our first example, here we have our namespace and first call, which holds the main statement. Then we have our string variable with value as null. This will be the major variable, which will lead to our expected exception. Then we have a simple if condition where we will check if the length of our variable is zero or not and if it is zero it will move to the next step and print the value. But the code will not move to the final print line as it will encounter an exception while within the if. Refer the below attached screenshot for output:
Output:
Here, the output is just as our first example, “Unhandled Exception” because the exception is the same, we tried to implement a function here but as explained our variable has a null value which leads us to Null Reference Exception. Now that we have seen and understood how and why this null reference exception occurs, it is important to understand how we can avoid it for better functioning of the program.
How to Avoid NullReferenceException in C#?
The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement. We will demonstrate an example where we will avoid the occurrence of the exception and the code will move on.
Code:
using System;
class SampleProgram {
static void Main() {
string val = null;
if (val == null) {
Console.WriteLine("\n Value to the variable is null.");
}
else{
Console.WriteLine(val);
}
}
}
Output:
Code Explanation: Here we have our class which holds the main statement than a variable with a null value. Then we enter an if else statement, where the value of the variable is checked if it is null, the print statement will be printed and the program will terminate, if the value is not null, then it will move ahead and into else part, it will print the value. As expected our code printed that “Value to the variable is null.” because the value is null. If we try the same example with a string value, the program will proceed and the else part will be printed.
Conclusion
The NullReferenceException is encountered when we attempt to access a variable which holds a null value, it can be variable or object. The reference should not hold null value else the exception will be thrown. There are many situations where this can be seen and the simplest way to avoid the NullReferenceException is to check beforehand, before accessing the value.
Recommended Articles
This is a guide to C# NullReferenceException. Here we also discuss the introduction and how nullreferenceexception works in c# along with examples and its code implementation. You may also have a look at the following articles to learn more –