C#NullReferenceException

NullReferenceException is thrown in C# when you try to access a property of method on an object of null reference. Hence the name Null Reference. Simply put, the object is null.

The object here could be a string, a class object, or anything.

Example to Recreate NullReferenceException

Following is a simple example to recreate the scenario where NullReferenceException is thrown.

Program.cs

using System;

namespace CSharpExamples {

    class Program {
        static void Main(string[] args) {
            string str = null;
            Console.WriteLine(str.Substring(5));
        }
    }
}

Here we defined a string with null value. When we try to access a method like Substring() on the string variable with null, NullReferenceException is thrown as shown in the following output.

Output

PS D:\workspace\csharp\HelloWorld> dotnet run

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at CSharpExamples.Program.Main(String[] args) in D:\workspace\csharp\HelloWorld\Program.cs:line 8

How to Solve or Handle NullReferenceException?

There are many ways in which you can handle NullReferenceException.

Using Try-Catch

Well, the first is what we do to handle any exception. Its using C# try-catch. Use try catch statement around the code which has potential to the NullReferenceException. Then write your logic to work around the exception.

Program.cs

using System;

namespace CSharpExamples {

    class Program {
        static void Main(string[] args) {
            string str = null;
            try{
                Console.WriteLine(str.Substring(5));
            } catch(NullReferenceException err){
                Console.WriteLine("Please check the string str.");
                Console.WriteLine(err.Message);
            }
            Console.WriteLine("Continuing with other statments..");
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Please check the string str.
Object reference not set to an instance of an object.
Continuing with other statments..

Check if reference is null

You can also check if the object is null, and apply the method or access property only if the reference is not null.

Program.cs

using System;

namespace CSharpExamples {

    class Program {
        static void Main(string[] args) {
            string str = null;
            if(str!=null){
                Console.WriteLine(str.Substring(5));
            } else {
                Console.WriteLine("str is null.");
            }
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
str is null.

Conclusion

In this C# Tutorial, we learned how NullReferenceException occurs in C#, ways to handle the exception using try-catch or regular check using if statement.