How to remove System NullReferenceException object reference not set to an instance of an object

A NullReferenceException happens when you try to access a reference variable that isn’t referencing any object. If a reference variable isn’t referencing an object, then it’ll be treated as null. The run-time will tell you that you are trying to access an object, when the variable is null by issuing a NullReferenceException.

Reference variables in c# and JavaScript are similar in concept to pointers in C and C++. Reference types default to null to indicate that they are not referencing any object. Hence, if you try and access the object that is being referenced and there isn’t one, you will get a NullReferenceException.

When you get a NullReferenceException in your code it means that you have forgotten to set a variable before using it. The error message will look something like:

NullReferenceException: Object reference not set to an instance of an object at Example.Start () [0x0000b] in /Unity/projects/nre/Assets/Example.cs:10

This error message says that a NullReferenceException happened on line 10 of the script file Example.cs. Also, the message says that the exception happened inside the Start() function. This makes the Null Reference Exception easy to find and fix. In this example, the code is:

//c# example using UnityEngine; using System.Collections; public class Example : MonoBehaviour { // Use this for initialization void Start () { __GameObject__The fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject's functionality is defined by the Components attached to it. [More info](class-GameObject.html)<span class="tooltipGlossaryLink">See in [Glossary](Glossary.html#GameObject)</span> go = GameObject.Find("wibble"); Debug.Log(go.name); } }

The code simply looks for a game object called “wibble”. In this example there is no game object with that name, so the Find() function returns null. On the next line (line 9) we use the go variable and try and print out the name of the game object it references. Because we are accessing a game object that doesn’t exist the run-time gives us a NullReferenceException

Null Checks

Although it can be frustrating when this happens it just means the script needs to be more careful. The solution in this simple example is to change the code like this:

using UnityEngine; using System.Collections; public class Example : MonoBehaviour { void Start () { GameObject go = GameObject.Find("wibble"); if (go) { Debug.Log(go.name); } else { Debug.Log("No game object called wibble found"); } } }

Now, before we try and do anything with the go variable, we check to see that it is not null. If it is null, then we display a message.

Try/Catch Blocks

Another cause for NullReferenceException is to use a variable that should be initialised in the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary
. If you forget to do this, then the variable will be null. A different way to deal with NullReferenceException is to use try/catch block. For example, this code:

using UnityEngine; using System; using System.Collections; public class Example2 : MonoBehaviour { public Light myLight; // set in the inspector void Start () { try { myLight.color = Color.yellow; } catch (NullReferenceException ex) { Debug.Log("myLight was not set in the inspector"); } } }

In this code example, the variable called myLight is a Light which should be set in the Inspector window. If this variable is not set, then it will default to null. Attempting to change the color of the light in the try block causes a NullReferenceException which is picked up by the catch block. The catch block displays a message which might be more helpful to artists and game designers, and reminds them to set the light in the inspector.

Summary

  • NullReferenceException happens when your script code tries to use a variable which isn’t set (referencing) and object.
  • The error message that appears tells you a great deal about where in the code the problem happens.
  • NullReferenceException can be avoided by writing code that checks for null before accessing an object, or uses try/catch blocks.

Debugging System.NullReferenceException - Object reference not set to an instance of an object

TOC

Time for another post in the series Debugging common .NET exceptions. Today's exception is, without a doubt, the error most people have experienced: System.NullReferenceException. The exception happens when you try to invoke a reference that you were expecting to point to an object but in fact, points to null. Let's get started!

How to remove System NullReferenceException object reference not set to an instance of an object

Handling the error

There are some clever ways to avoid a NullReferenceException, but before we start looking into those, let us see how the exception can be caught. Being a plain old C# exception, NullReferenceException can be caught using a try/catch:

try { string s = null; s.ToString(); } catch (NullReferenceException e) { // Do something with e, please. }

Running the code above will produce the following error:

System.NullReferenceException: Object reference not set to an instance of an object.

Debugging the error

We already know why the exception is happening. Something is null. When looking at the code above, it's clear that s is null and the stack trace even tells us that:

How to remove System NullReferenceException object reference not set to an instance of an object

Sometimes spotting what is null can be hard. Take a look at the following example:

var street = service.GetUser().Address.Street;

If the code above throws a NullReferenceException, what is null? service? The result of GetUser()? Address? At first glance, Visual Studio isn't exactly helpful either:

How to remove System NullReferenceException object reference not set to an instance of an object

There is a range of different ways to find out what is going on. Let's look at the most commonly used ones.

Splitting chained method-calls to multiple lines

Spotting which call that caused an error is a lot easier if the calls are split into multiple lines:

var service = new Service(); var user = service.GetUser(); var address = user.Address; var street = address.Street;

Running the code reveals the actual call causing the exception:

How to remove System NullReferenceException object reference not set to an instance of an object

In the example above user.Address returns null, why address.Street causes the NullReferenceException.

While splitting code into atoms like this can help debug what is going wrong, it's not preferable in terms of readability (IMO).

Using Null Reference Analysis in Visual Studio

If you are on Visual Studio 2017 or newer (if not, now is the time to upgrade), you will have the Null Reference Analysis feature available. With this in place, Visual Studio can show you exactly what is null. Let's change the example back to method-chaining:

var street = service.GetUser().Address.Street;

To enable the analysis go to Debug | Windows | Exception Settings. Check Common Language Runtime Exceptions (if not already checked) or extend the node and check the exceptions you are interested in. In this case, you can check System.NullReferenceException. When running the code, the debugger breaks on the NullReferenceException and you now see the Exception Thrown window:

How to remove System NullReferenceException object reference not set to an instance of an object

Voila! The window says "ConsoleApp18.User.Address.get returned null". Exactly what we wanted to see. This will require you to run the code locally, though. If you are experiencing the exception on your production website, the Null Reference Analysis will not be available, since this is a feature belonging to Visual Studio (unfortunately). With that said, you can attach a debugger to a remote site running on Azure as explained here: Introduction to Remote Debugging on Azure Web Sites.

Fixing the error

There are various ways to fix NullReferenceException. We'll start with the simple (but dirty) approach.

Using null checks

If null is an allowed value of an object, you will need to check for it. The most simple solution is to include a bunch of if-statements.

if (service != null) { var user = service.GetUser(); if (user != null) { var address = user.Address; if (address != null) { var street = address.Street; } } }

The previous code will only reach address.Street if everything else is not null. We can probably agree that the code isn't exactly pretty. Having multiple nested steps is harder to read. We can reverse the if-statements:

if (service == null) return; var user = service.GetUser(); if (user == null) return; var address = user.Address; if (address == null) return; var street = address.Street;

Simpler, but still a lot of code to get a street name.

Using null-conditional operator

C# 6 introduced a piece of syntactic sugar to check for null: null-conditional operator. Let's change the method-chain example from before to use the "new" operator:

var user = service?.GetUser()?.Address?.Street;

The ? to the right of each variable, corresponds the nested if-statements from previously. But with much less code.

Use Debug.Assert during development

When getting a NullReferenceException it can be hard to spot the intent with the code from the original developer. Rather than including if-statements, it can be clearer for future authors of your code to use the Debug.Assert-method. Much like in a xUnit or NUnit test, you use Assert to verify the desired state on your objects. In the example from above, the service object could have come through a parameter or a constructor injected dependency:

class MyClass { Service service; public MyClass(Service service) { this.service = service; } public string UserStreet() { return service.GetUser().Address.Street; } }

To make a statement in your code that service should never be allowed to have the value of null, extend the constructor:

public MyClass(Service service) { Debug.Assert(service != null); this.service = service; }

In the case MyClass is constructed with null, the following error is shown when running locally:

How to remove System NullReferenceException object reference not set to an instance of an object

Use nullable reference types in C# 8.0

When designing code you often end up expecting parameters to be not null but end up checking for null to avoid a NullReferenceException. As you already know, all reference types in C# can take the value of null. Value types like int and boolean cannot take a value of null unless explicitely specified using the nullable value type (int? or Nullable<int>). Maybe it should have been the other way around with reference types all along?

C# 8 can fix this with nullable reference types (maybe NOT nullable reference types is a better name). Since this is a breaking change, it is launched as an opt-in feature. Nullable reference types are a great way to avoid NullReferenceExceptions, since you are very explicit about where you expect null and where not.

To enable not nullable reference types, create a new .NET Core 3 project and add the following to the csproj file:

<LangVersion>8.0</LangVersion> <Nullable>enable</Nullable>

You should be on C# 8 already, but to make it explicit, I've added the LangVersion element. The Nullable element enables nullable reference types. Out of the box, C# 8 creates a warning if it identifies the use of null where a value is expected. Let's see how that looks:

class Program { static void Main() { new Program().SayHello(null); } public void SayHello(string msg) { Console.WriteLine(msg); } }

When compiling we see the following warning:

Program.cs(9,36): warning CS8625: Cannot convert null literal to non-nullable reference type. [C:\projects\core3\core3.csproj]

I know you are not one of them, but some people developed a warning-resistance which means that warnings are simply ignored. To overcome this, make sure that errors like this causes build errors over warnings by adding the following to csproj:

<WarningsAsErrors>CS8602,CS8603,CS8618,CS8625</WarningsAsErrors>

This will tell the C# compiler to treat these four nullable reference type warnings as errors instead.

Just to make it clear, allowing null in the msg parameter, you use the ? characters as with value types:

public void SayHello(string? msg) { ... }

Logging and monitoring

Logging and monitoring for null reference exceptions are a must. While some developers tempt to create control flow from exceptions (no-one should), null reference exceptions should never happen. This means that a System.NullReferenceException is a type of exception that should always be logged and fixed. A null check through either an if statement or the null-conditional operator is always the preferred way of handling potential null values. But make sure to implement a logging strategy that logs all uncaught exceptions, including the System.NullReferenceException.

When logging a System.NullReferenceException in a log file, database, elmah.io, or similar, it can be hard to spot what is null. You typically only see the method-name that causes the NullReferenceException and the Null Reference Analysis feature is only available while debugging inside Visual Studio. I will recommend you to always Include filename and line number in stack traces. This will pinpoint the exact line where the error happens.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

How to remove System NullReferenceException object reference not set to an instance of an object

See how we can help you monitor your website for crashes Monitor your website

How do I remove object reference not set to an instance of an object?

How to Avoid Object Reference Not Set to an Instance of an Object?.
Explicitly check for null and ignore null values. ... .
Explicitly check for null and provide a default value. ... .
Explicitly check for null from method calls and throw a custom exception. ... .
Use Debug..

What is NullReferenceException object reference not set to an instance of an object?

The message "Object not set to an instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these: Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate' it)

What causes object reference not set to an instance of an object?

The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs.

How do I stop NullReferenceException?

Here are few useful methods:.
Method 1 - use if statement. Check the property before accessing instance members. ... .
Method 2 - use Null Conditional Operator( ? ) It will check the property before accessing instance members. ... .
Method 3 - use GetValueOrDefault() ... .
Method 4 - use Null Coalescing Operator. ... .
Method 5 - use ?: operator..