Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

NullReferenceException classe

 

Date de publication : novembre 2016

Exception levée au moment d'une tentative de suppression de la référence à une référence d'objet null.

Espace de noms:   System
Assembly:  mscorlib (dans mscorlib.dll)

System.Object
  System.Exception
    System.SystemException
      System.NullReferenceException

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class NullReferenceException : SystemException

NomDescription
System_CAPS_pubmethodNullReferenceException()

Initialise une nouvelle instance de la NullReferenceException classe, en définissant le Message propriété de la nouvelle instance à un message système décrivant l’erreur, tel que « la valeur 'null' a été trouvée dans lequel une instance d’un objet était requise. » Ce message prend en compte la culture système en cours.

System_CAPS_protmethodNullReferenceException(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe NullReferenceException avec des données sérialisées.

System_CAPS_pubmethodNullReferenceException(String)

Initialise une nouvelle instance de la classe NullReferenceException avec un message d'erreur spécifié.

System_CAPS_pubmethodNullReferenceException(String, Exception)

Initialise une nouvelle instance de la classe NullReferenceException avec un message d'erreur spécifié et une référence à l'exception interne ayant provoqué cette exception.

NomDescription
System_CAPS_pubpropertyData

Obtient une collection de paires clé/valeur qui fournissent des informations supplémentaires définies par l’utilisateur sur l’exception.(Hérité de Exception.)

System_CAPS_pubpropertyHelpLink

Obtient ou définit un lien vers le fichier d'aide associé à cette exception.(Hérité de Exception.)

System_CAPS_pubpropertyHResult

Obtient ou définit HRESULT, valeur numérique codée qui est assignée à une exception spécifique.(Hérité de Exception.)

System_CAPS_pubpropertyInnerException

Obtient l'instance Exception qui a provoqué l'exception actuelle.(Hérité de Exception.)

System_CAPS_pubpropertyMessage

Obtient un message qui décrit l'exception actuelle.(Hérité de Exception.)

System_CAPS_pubpropertySource

Obtient ou définit le nom de l'application ou de l'objet qui est à l'origine de l'erreur.(Hérité de Exception.)

System_CAPS_pubpropertyStackTrace

Obtient une représentation sous forme de chaîne des objets immédiats sur la pile des appels. (Hérité de Exception.)

System_CAPS_pubpropertyTargetSite

Obtient la méthode qui lève l'exception actuelle.(Hérité de Exception.)

NomDescription
System_CAPS_pubmethodEquals(Object)

Détermine si l'objet spécifié est identique à l'objet actuel.(Hérité de Object.)

System_CAPS_protmethodFinalize()

Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de nettoyage avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)

System_CAPS_pubmethodGetBaseException()

En cas de substitution dans une classe dérivée, retourne la Exception qui est à l'origine d'une ou de plusieurs exceptions ultérieures.(Hérité de Exception.)

System_CAPS_pubmethodGetHashCode()

Fait office de fonction de hachage par défaut.(Hérité de Object.)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

En cas de substitution dans une classe dérivée, définit SerializationInfo avec des informations sur l'exception.(Hérité de Exception.)

System_CAPS_pubmethodGetType()

Obtient le type au moment de l'exécution de l'instance actuelle.(Hérité de Exception.)

System_CAPS_protmethodMemberwiseClone()

Crée une copie superficielle du Object actuel.(Hérité de Object.)

System_CAPS_pubmethodToString()

Crée et retourne une chaîne représentant l'exception actuelle.(Hérité de Exception.)

NomDescription
System_CAPS_proteventSerializeObjectState

Se produit quand une exception est sérialisée pour créer un objet d'état d'exception qui contient des données sérialisées concernant l'exception.(Hérité de Exception.)

A T:System.NullReferenceException exception is thrown when you try to access a member on a type whose value is null. A T:System.NullReferenceException exception typically reflects developer error and is thrown in the following scenarios:

  • You've forgotten to instantiate a reference type. In the following example, names is declared but never instantiated:

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main(string[] args)
       {
          int value = Int32.Parse(args[0]);
          List<String> names;
          if (value > 0)
             names = new List<String>();
    
          names.Add("Major Major Major");       
       }
    }
    // Compilation displays a warning like the following:
    //    Example1.vb(10) : warning BC42104: Variable //names// is used before it 
    //    has been assigned a value. A null reference exception could result 
    //    at runtime.
    //    
    //          names.Add("Major Major Major")
    //          ~~~~~
    // The example displays output like the following output:
    //    Unhandled Exception: System.NullReferenceException: Object reference 
    //    not set to an instance of an object.
    //       at Example.Main()
    

    Some compilers issue a warning when they compile this code. Others issue an error, and the compilation fails. To address this problem, instantiate the object so that its value is no longer null. The following example does this by calling a type's class constructor.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<String> names = new List<String>();
          names.Add("Major Major Major");
       }
    }
    
  • You've forgotten to dimension an array before initializing it. In the following example, values is declared to be an integer array, but the number of elements that it contains is never specified. The attempt to initialize its values therefore thrown a T:System.NullReferenceException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
           int[] values = null;
           for (int ctr = 0; ctr <= 9; ctr++)
              values[ctr] = ctr * 2;
    
           foreach (var value in values)
              Console.WriteLine(value);   
       }
    }
    // The example displays the following output:
    //    Unhandled Exception: 
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Example.Main()
    

    You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does.

    using System;
    
    public class Example
    {
       public static void Main()
       {
           int[] values = new int[10];
           for (int ctr = 0; ctr <= 9; ctr++)
              values[ctr] = ctr * 2;
    
           foreach (var value in values)
              Console.WriteLine(value);   
       }
    }
    // The example displays the following output:
    //    0
    //    2
    //    4
    //    6
    //    8
    //    10
    //    12
    //    14
    //    16
    //    18
    

    For more information on declaring and initializing arrays, see Arrays (C# Programming Guide) and Arrays in Visual Basic.

  • You get a null return value from a method, and then call a method on the returned type. This sometimes is the result of a documentation error; the documentation fails to note that a method call can return null. In other cases, your code erroneously assumes that the method will always return a non-null value.

    The code in the following example assumes that the M:System.Array.Find``1(``0[],System.Predicate{``0}) method always returns Person object whose FirstName field matches a search string. Because there is no match, the runtime throws a T:System.NullReferenceException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Person[] persons = Person.AddRange( new String[] { "Abigail", "Abra", 
                                              "Abraham", "Adrian", "Ariella", 
                                              "Arnold", "Aston", "Astor" } );    
          String nameToFind = "Robert";
          Person found = Array.Find(persons, p => p.FirstName == nameToFind);
          Console.WriteLine(found.FirstName);
       }
    }
    
    public class Person
    {
       public static Person[] AddRange(String[] firstNames) 
       {
          Person[] p = new Person[firstNames.Length];
          for (int ctr = 0; ctr < firstNames.Length; ctr++)
             p[ctr] = new Person(firstNames[ctr]);
    
          return p;
       }
    
       public Person(String firstName)
       {
          this.FirstName = firstName;
       } 
    
       public String FirstName;
    }
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException: 
    //       Object reference not set to an instance of an object.
    //          at Example.Main()
    

    To address this problem, test the method's return value to ensure that it is not null before calling any of its members, as the following example does.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Person[] persons = Person.AddRange( new String[] { "Abigail", "Abra", 
                                              "Abraham", "Adrian", "Ariella", 
                                              "Arnold", "Aston", "Astor" } );    
          String nameToFind = "Robert";
          Person found = Array.Find(persons, p => p.FirstName == nameToFind);
          if (found != null)
             Console.WriteLine(found.FirstName);
          else
             Console.WriteLine("{0} not found.", nameToFind);   
       }
    }
    
    public class Person
    {
       public static Person[] AddRange(String[] firstNames) 
       {
          Person[] p = new Person[firstNames.Length];
          for (int ctr = 0; ctr < firstNames.Length; ctr++)
             p[ctr] = new Person(firstNames[ctr]);
    
          return p;
       }
    
       public Person(String firstName)
       {
          this.FirstName = firstName;
       } 
    
       public String FirstName;
    }
    // The example displays the following output:
    //        Robert not found
    
  • You're using an expression (for example, you're chaining a list of methods or properties together) to retrieve a value and, although you're checking whether the value is null, the runtime still throws a T:System.NullReferenceException exception. This occurs because one of the intermediate values in the expression returns null. As a result, your rest for null is never evaluated.

    The following example defines a Pages object that caches information about web pages, which are presented by Page objects. The Example.Main method checks whether the current web page has a non-null title and, if it does, displays the title. Despite this check, however, the method throws a T:System.NullReferenceException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          var pages = new Pages();
          if (! String.IsNullOrEmpty(pages.CurrentPage.Title)) {
             String title = pages.CurrentPage.Title;
             Console.WriteLine("Current title: '{0}'", title);
          }
       }
    }
    
    public class Pages 
    {
       Page[] page = new Page[10];
       int ctr = 0;
    
       public Page CurrentPage
       {
          get { return page[ctr]; }
          set {
             // Move all the page objects down to accommodate the new one.
             if (ctr > page.GetUpperBound(0)) {
                for (int ndx = 1; ndx <= page.GetUpperBound(0); ndx++)
                   page[ndx - 1] = page[ndx];
             }    
             page[ctr] = value;
             if (ctr < page.GetUpperBound(0))
                ctr++; 
          }
       }
    
       public Page PreviousPage
       {
          get {
             if (ctr == 0) { 
                if (page[0] == null)
                   return null;
                else
                   return page[0];
             }
             else {
                ctr--;
                return page[ctr + 1];
             }
          }
       }         
    }
    
    public class Page
    {
       public Uri URL;
       public String Title;
    }
    // The example displays the following output:
    //    Unhandled Exception: 
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Example.Main()
    

    The exception is thrown because pages.CurrentPage returns null if no page information is stored in the cache. This exception can be corrected by testing the value of the CurrentPage property before retrieving the current Page object's Title property, as the following example does:

    using System;
    
    public class Example
    {
       public static void Main()
       {
          var pages = new Pages();
          Page current = pages.CurrentPage;
          if (current != null) {  
             String title = current.Title;
             Console.WriteLine("Current title: '{0}'", title);
          }
          else {
             Console.WriteLine("There is no page information in the cache.");
          }   
       }
    }
    // The example displays the following output:
    //       There is no page information in the cache.
    
  • You're enumerating the elements of an array that contains reference types, and your attempt to process one of the elements throws a T:System.NullReferenceException exception.

    The following example defines a string array. A for statement enumerates the elements in the array and calls each string's M:System.String.Trim method before displaying the string.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] values = { "one", null, "two" };
          for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
             Console.Write("{0}{1}", values[ctr].Trim(), 
                           ctr == values.GetUpperBound(0) ? "" : ", "); 
          Console.WriteLine();
       }
    }
    // The example displays the following output:
    //    Unhandled Exception: 
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Example.Main()
    

    This exception occurs if you assume that each element of the array must contain a non-null value, and the value of the array element is in fact null. The exception can be eliminated by testing whether the element is null before performing any operation on that element, as the following example shows.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] values = { "one", null, "two" };
          for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
             Console.Write("{0}{1}", 
                           values[ctr] != null ? values[ctr].Trim() : "", 
                           ctr == values.GetUpperBound(0) ? "" : ", "); 
          Console.WriteLine();
       }
    }
    // The example displays the following output:
    //       one, , two
    
  • A T:System.NullReferenceException exception is thrown by a method that is passed null. Some methods validate the arguments that are passed to them. If they do and one of the arguments is null, the method throws an T:System.ArgumentNullException exception. Otherwise, it throws a T:System.NullReferenceException exception. The following example illustrates this scenario.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<String> names = GetData();
          PopulateNames(names);
       }
    
       private static void PopulateNames(List<String> names)
       {
          String[] arrNames = { "Dakota", "Samuel", "Nikita",
                                "Koani", "Saya", "Yiska", "Yumaevsky" };
          foreach (var arrName in arrNames)
             names.Add(arrName);
       }
    
       private static List<String> GetData() 
       {
          return null;   
    
       }
    }
    // The example displays output like the following:
    //    Unhandled Exception: System.NullReferenceException: Object reference 
    //    not set to an instance of an object.
    //       at Example.PopulateNames(List`1 names)
    //       at Example.Main()
    

    To address this issue, make sure that the argument passed to the method is not null, or handle the thrown exception in a try…catch…finally block. For more information, see Handling and Throwing Exceptions.

The following Microsoft intermediate language (MSIL) instructions throw T:System.NullReferenceException: callvirt, cpblk, cpobj, initblk, ldelem.<type>, ldelema, ldfld, ldflda, ldind.<type>, ldlen, stelem.<type>, stfld, stind.<type>, throw, and unbox.

NullReferenceException uses the HRESULT COR_E_NULLREFERENCE, which has the value 0x80004003.

For a list of initial property values for an instance of T:System.NullReferenceException, see the M:System.NullReferenceException.#ctor constructors.

Handling NullReferenceException in release code

It's usually better to avoid a NullReferenceException than to handle it after it occurs. Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. A NullReferenceException is often a non-recoverable error. In these cases, letting the exception stop the app might be the best alternative.

However, there are many situations where handling the error can be useful:

  • Your app can ignore objects that are null. For example, if your app retrieves and processes records in a database, you might be able to ignore some number of bad records that result in null objects. Recording the bad data in a log file or in the application UI might be all you have to do.

  • You can recover from the exception. For example, a call to a web service that returns a reference type might return null if the connection is lost or the connection times out. You can attempt to reestablish the connection and try the call again.

  • You can restore the state of your app to a valid state. For example, you might be performing a multi-step task that requires you to save information to a data store before you call a method that throws a NullReferenceException. If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app.

  • You want to report the exception. For example, if the error was caused by a mistake from the user of your app, you can generate a message to help him supply the correct information. You can also log information about the error to help you fix the problem. Some frameworks, like ASP.NET, have a high-level exception handler that captures all errors to that the app never crashes; in that case, logging the exception might be the only way you can know that it occurs.

Plateforme Windows universelle
Disponible depuis 8
.NET Framework
Disponible depuis 1.1
Bibliothèque de classes portable
Pris en charge dans : plateformes .NET portables
Silverlight
Disponible depuis 2.0
Silverlight pour Windows Phone
Disponible depuis 7.0
Windows Phone
Disponible depuis 8.1

Tous les membres statiques publics ( Shared en Visual Basic) de ce type sont thread-safe. Les membres d’instance n’ont pas la garantie d’être thread-safe.

Retour au début
Afficher: