Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
NullReferenceException

NullReferenceException

Aug 04 2023

NullReferenceException (NRE) is a .NET exception that occurs when a developer tries to access a null reference.

In C#, reference type variables store references to objects. A reference may have a value of null: in this case, it does not point to any object in memory. The default value for reference types is null.

Let's consider a simple synthetic example:

string str = null;
var len = str.Length;
....

The str variable takes the null value. This causes NullReferenceException to be thrown when a programmer attempts to access the Length property.

Errors are often not so obvious. Let's take a look at a code fragment from an open-source project:

public Palette GlobalPalette
{
  get {....}
  set
  {
    SetTagValue("GlobalPalette", (value != null) ? null : value.Data);
  }
}

Developers made a mistake when using the ternary operator — they mixed up operands. The value variable is checked for null. If value is null, an attempt will be made to access the Data property. This will result in throwing a NullReferenceException because value stores a null reference.

Calling the SetTagValue method this way is correct:

SetTagValue("GlobalPalette", (value != null) ? value.Data : null);

To learn more about the reasons for NullReferenceException, as well as how to fix exceptions and how to avoid them, see the article: "NullReferenceException in C#. What is it and how to fix it?"

Popular related articles