﻿# NullReferenceException

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

```cpp
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:

```cpp
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:

```cpp
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?\]\(https://pvs\-studio\.com/en/blog/posts/csharp/1049/\)"