Unicorn with delicious cookie
Nous utilisons des cookies pour améliorer votre expérience de navigation. En savoir plus
Accepter
to the top
>
>
>
NullReferenceException

NullReferenceException

04 Aoû 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

S'abonner

Comments (0)

close comment form
close form

Remplissez le formulaire ci‑dessous en 2 étapes simples :

Vos coordonnées :

Étape 1
Félicitations ! Voici votre code promo !

Type de licence souhaité :

Étape 2
Team license
Enterprise licence
** En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité
close form
Demandez des tarifs
Nouvelle licence
Renouvellement de licence
--Sélectionnez la devise--
USD
EUR
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
La licence PVS‑Studio gratuit pour les spécialistes Microsoft MVP
close form
Pour obtenir la licence de votre projet open source, s’il vous plait rempliez ce formulaire
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
I want to join the test
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
check circle
Votre message a été envoyé.

Nous vous répondrons à


Si l'e-mail n'apparaît pas dans votre boîte de réception, recherchez-le dans l'un des dossiers suivants:

  • Promotion
  • Notifications
  • Spam