Our website uses cookies to enhance your browsing experience.
Accept
to the top
close form

Fill out the form in 2 simple steps below:

Your contact information:

Step 1
Congratulations! This is your promo code!

Desired license type:

Step 2
Team license
Enterprise license
** By clicking this button you agree to our Privacy Policy statement
close form
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
* By clicking this button you agree to our Privacy Policy statement

close form
Free PVS‑Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

close form
To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

close form
I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

close form
check circle
Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
>
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


Comments (0)

Next comments next comments
close comment form