NullReferenceException Clase

Definición

Excepción que se produce cuando hay un intento de desreferenciar una referencia de objeto NULL.

public ref class NullReferenceException : Exception
public ref class NullReferenceException : SystemException
public class NullReferenceException : Exception
public class NullReferenceException : SystemException
[System.Serializable]
public class NullReferenceException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class NullReferenceException : SystemException
type NullReferenceException = class
    inherit Exception
type NullReferenceException = class
    inherit SystemException
[<System.Serializable>]
type NullReferenceException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type NullReferenceException = class
    inherit SystemException
Public Class NullReferenceException
Inherits Exception
Public Class NullReferenceException
Inherits SystemException
Herencia
NullReferenceException
Herencia
NullReferenceException
Atributos

Comentarios

Se produce una NullReferenceException excepción cuando se intenta acceder a un miembro en un tipo cuyo valor es null. Normalmente, una NullReferenceException excepción refleja el error del desarrollador y se produce en los escenarios siguientes:

Note

Puede evitar la mayoría NullReferenceException de las excepciones en C# mediante el operador condicional null (?.) o el operador de fusión null (??). Para más información, consulte Tipos de referencia que admiten un valor NULL. En los siguientes ejemplos de C# se supone que el contexto que acepta valores NULL está deshabilitado (no se recomienda).

  • Olvidó crear una instancia de un tipo de referencia. En el ejemplo siguiente, names se declara pero nunca se crea una instancia (la línea afectada se comenta en el ejemplo de C#, ya que no se compila):

    using System.Collections.Generic;
    
    public class UseBeforeAssignExample
    {
        public static void Main(string[] args)
        {
            int value = int.Parse(args[0]);
            List<string> names;
            if (value > 0)
                names = [];
    
            //names.Add("Major Major Major");
        }
    }
    
    // Compilation displays a warning like the following:
    //    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 UseBeforeAssignExample.Main()
    
    open System
    
    [<EntryPoint>]
    let main args =
        let value = Int32.Parse args[0]
        // Set names to null, don't initialize it. 
        let mutable names = Unchecked.defaultof<ResizeArray<string>>
        if value > 0 then
            names <- ResizeArray()
        names.Add "Major Major Major"
        0
    // Compilation does not display a warning as this is an extremely rare occurance in F#.
    // Creating a value without initalizing either requires using 'null' (not possible
    // on types defined in F# without [<AllowNullLiteral>]) or Unchecked.defaultof.
    //
    // 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()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As List(Of String)
          names.Add("Major Major Major")       
       End Sub
    End Module
    ' 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()
    

    Algunos compiladores emiten una advertencia cuando compilan este código. Otros emiten un error y se produce un error en la compilación. Para solucionar este problema, cree una instancia del objeto para que su valor ya nullno sea . En el ejemplo siguiente se realiza mediante una llamada al constructor de clase de un tipo.

    using System.Collections.Generic;
    
    public class AnotherExample
    {
        public static void Main()
        {
            List<string> names = ["Major Major Major"];
        }
    }
    
    let names = ResizeArray()
    names.Add "Major Major Major"
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As New List(Of String)()
          names.Add("Major Major Major")       
       End Sub
    End Module
    
  • Olvidó dimensionar una matriz antes de inicializarla. En el ejemplo siguiente, values se declara como una matriz de enteros, pero nunca se especifica el número de elementos que contiene. Por lo tanto, el intento de inicializar sus valores produce una NullReferenceException excepción.

    int[] values = null;
    for (int ctr = 0; ctr <= 9; ctr++)
        values[ctr] = ctr * 2;
    
    foreach (int 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 Array3Example.Main()
    
    let values: int[] = null
    for i = 0 to 9 do
        values[i] <- i * 2
    
    for value in values do
        printfn $"{value}"
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
           Dim values() As Integer
           For ctr As Integer = 0 To 9
              values(ctr) = ctr * 2
           Next
              
           For Each value In values
              Console.WriteLine(value)
           Next      
       End Sub
    End Module
    ' The example displays the following output:
    '    Unhandled Exception: 
    '       System.NullReferenceException: Object reference not set to an instance of an object.
    '       at Example.Main()
    

    Puede eliminar la excepción declarando el número de elementos de la matriz antes de inicializarlo, como hace el ejemplo siguiente.

    int[] values = new int[10];
    for (int ctr = 0; ctr <= 9; ctr++)
        values[ctr] = ctr * 2;
    
    foreach (int value in values)
        Console.WriteLine(value);
    
    // The example displays the following output:
    //    0
    //    2
    //    4
    //    6
    //    8
    //    10
    //    12
    //    14
    //    16
    //    18
    
    let values = Array.zeroCreate<int> 10
    for i = 0 to 9 do
        values[i] <- i * 2
    
    for value in values do
        printfn $"{value}"
    // The example displays the following output:
    //    0
    //    2
    //    4
    //    6
    //    8
    //    10
    //    12
    //    14
    //    16
    //    18
    
    Module Example
       Public Sub Main()
           Dim values(9) As Integer
           For ctr As Integer = 0 To 9
              values(ctr) = ctr * 2
           Next
              
           For Each value In values
              Console.WriteLine(value)
           Next      
       End Sub
    End Module
    ' The example displays the following output:
    '    0
    '    2
    '    4
    '    6
    '    8
    '    10
    '    12
    '    14
    '    16
    '    18
    

    Para obtener más información sobre cómo declarar e inicializar matrices, vea Matrices y matrices.

  • Obtiene un valor devuelto null de un método y, a continuación, llama a un método en el tipo devuelto. Esto a veces es el resultado de un error de documentación; La documentación no puede tener en cuenta que una llamada al método puede devolver null. En otros casos, el código supone erróneamente que el método siempre devolverá un valor distinto de NULL.

    El código del ejemplo siguiente supone que el método siempre devuelve Person el Array.Find objeto cuyo FirstName campo coincide con una cadena de búsqueda. Dado que no hay ninguna coincidencia, el tiempo de ejecución produce una NullReferenceException excepción.

    public static void NoCheckExample()
    {
        Person[] persons = Person.AddRange([ "Abigail", "Abra",
                                          "Abraham", "Adrian", "Ariella",
                                          "Arnold", "Aston", "Astor" ]);
        string nameToFind = "Robert";
        Person found = Array.Find(persons, p => p.FirstName == nameToFind);
        Console.WriteLine(found.FirstName);
    }
    
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    
    open System
    
    type Person(firstName) =
        member _.FirstName = firstName
    
        static member AddRange(firstNames) =
            Array.map Person firstNames
    
    let persons = 
        [| "Abigail"; "Abra"; "Abraham"; "Adrian"
           "Ariella"; "Arnold"; "Aston"; "Astor" |]
        |> Person.AddRange
    
    let nameToFind = "Robert"
    let found = Array.Find(persons, fun p -> p.FirstName = nameToFind)
    
    printfn $"{found.FirstName}"
    
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    //          at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
          Dim persons() As Person = Person.AddRange( { "Abigail", "Abra",
                                                       "Abraham", "Adrian",
                                                       "Ariella", "Arnold", 
                                                       "Aston", "Astor" } )    
          Dim nameToFind As String = "Robert"
          Dim found As Person = Array.Find(persons, Function(p) p.FirstName = nameToFind)
          Console.WriteLine(found.FirstName)
       End Sub
    End Module
    
    Public Class Person
       Public Shared Function AddRange(firstNames() As String) As Person()
          Dim p(firstNames.Length - 1) As Person
          For ctr As Integer = 0 To firstNames.Length - 1
             p(ctr) = New Person(firstNames(ctr))
          Next   
          Return p
       End Function
       
       Public Sub New(firstName As String)
          Me.FirstName = firstName
       End Sub 
       
       Public FirstName As String
    End Class
    ' The example displays the following output:
    '       Unhandled Exception: System.NullReferenceException: 
    '       Object reference not set to an instance of an object.
    '          at Example.Main()
    

    Para solucionar este problema, pruebe el valor devuelto del método para asegurarse de que no null es antes de llamar a ninguno de sus miembros, como hace el ejemplo siguiente.

    public static void ExampleWithNullCheck()
    {
        Person[] persons = Person.AddRange([ "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($"'{nameToFind}' not found.");
    }
    
    // The example displays the following output:
    //        'Robert' not found
    
    open System
    
    [<AllowNullLiteral>]
    type Person(firstName) =
        member _.FirstName = firstName
    
        static member AddRange(firstNames) =
            Array.map Person firstNames
    
    let persons = 
        [| "Abigail"; "Abra"; "Abraham"; "Adrian"
           "Ariella"; "Arnold"; "Aston"; "Astor" |]
        |> Person.AddRange
    
    let nameToFind = "Robert"
    let found = Array.Find(persons, fun p -> p.FirstName = nameToFind)
    
    if found <> null then
        printfn $"{found.FirstName}"
    else 
        printfn $"{nameToFind} not found."
    
    // Using F#'s Array.tryFind function
    // This does not require a null check or [<AllowNullLiteral>]
    let found2 = 
        persons |> Array.tryFind (fun p -> p.FirstName = nameToFind)
    
    match found2 with
    | Some firstName ->
        printfn $"{firstName}"
    | None ->
        printfn $"{nameToFind} not found."
    
    // The example displays the following output:
    //        Robert not found.
    //        Robert not found.
    
    Module Example
       Public Sub Main()
          Dim persons() As Person = Person.AddRange( { "Abigail", "Abra",
                                                       "Abraham", "Adrian",
                                                       "Ariella", "Arnold", 
                                                       "Aston", "Astor" } )    
          Dim nameToFind As String = "Robert"
          Dim found As Person = Array.Find(persons, Function(p) p.FirstName = nameToFind)
          If found IsNot Nothing Then
             Console.WriteLine(found.FirstName)
          Else
             Console.WriteLine("{0} not found.", nameToFind)
          End If   
       End Sub
    End Module
    
    Public Class Person
       Public Shared Function AddRange(firstNames() As String) As Person()
          Dim p(firstNames.Length - 1) As Person
          For ctr As Integer = 0 To firstNames.Length - 1
             p(ctr) = New Person(firstNames(ctr))
          Next   
          Return p
       End Function
       
       Public Sub New(firstName As String)
          Me.FirstName = firstName
       End Sub 
       
       Public FirstName As String
    End Class
    ' The example displays the following output:
    '       Robert not found
    
  • Está usando una expresión (por ejemplo, encadenó una lista de métodos o propiedades juntos) para recuperar un valor y, aunque está comprobando si el valor es null, el tiempo de ejecución sigue produciendo una NullReferenceException excepción. Esto ocurre porque uno de los valores intermedios de la expresión devuelve null. Como resultado, la prueba de null nunca se evalúa.

    En el ejemplo siguiente se define un Pages objeto que almacena en caché información sobre las páginas web, que presentan Page los objetos . El Example.Main método comprueba si la página web actual tiene un título distinto de NULL y, si es así, muestra el título. Sin embargo, a pesar de esta comprobación, el método produce una NullReferenceException excepción.

    public class Chain1Example
    {
        public static void Main()
        {
            var pages = new Pages();
            if (!string.IsNullOrEmpty(pages.CurrentPage.Title))
            {
                string title = pages.CurrentPage.Title;
                Console.WriteLine($"Current title: '{title}'");
            }
        }
    }
    
    public class Pages
    {
        readonly 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] is 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 Chain1Example.Main()
    
    open System
    
    type Page() =
        [<DefaultValue>]
        val mutable public URL: Uri
        [<DefaultValue>]
        val mutable public Title: string
    
    type Pages() =
        let pages = Array.zeroCreate<Page> 10
        let mutable i = 0
    
        member _.CurrentPage
            with get () = pages[i]
            and set (value) =
                // Move all the page objects down to accommodate the new one.
                if i > pages.GetUpperBound 0 then
                    for ndx = 1 to pages.GetUpperBound 0 do
                        pages[ndx - 1] <- pages[ndx]
    
                pages[i] <- value
                if i < pages.GetUpperBound 0 then
                    i <- i + 1
    
        member _.PreviousPage =
            if i = 0 then
                if box pages[0] = null then
                    Unchecked.defaultof<Page>
                else
                    pages[0]
            else
                i <- i - 1
                pages[i + 1]
    
    let pages = Pages()
    if String.IsNullOrEmpty pages.CurrentPage.Title |> not then
        let title = pages.CurrentPage.Title
        printfn $"Current title: '{title}'"
    
    
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
          Dim pages As New Pages()
          Dim title As String = pages.CurrentPage.Title
       End Sub
    End Module
    
    Public Class Pages 
       Dim page(9) As Page
       Dim ctr As Integer = 0
       
       Public Property CurrentPage As Page
          Get
             Return page(ctr)
          End Get
          Set
             ' Move all the page objects down to accommodate the new one.
             If ctr > page.GetUpperBound(0) Then
                For ndx As Integer = 1 To page.GetUpperBound(0)
                   page(ndx - 1) = page(ndx)
                Next
             End If    
             page(ctr) = value
             If ctr < page.GetUpperBound(0) Then ctr += 1 
          End Set
       End Property
       
       Public ReadOnly Property PreviousPage As Page
          Get
             If ctr = 0 Then 
                If page(0) Is Nothing Then
                   Return Nothing
                Else
                   Return page(0)
                End If   
             Else
                ctr -= 1
                Return page(ctr + 1)
             End If
          End Get
       End Property         
    End Class
    
    Public Class Page
       Public URL As Uri
       Public Title As String
    End Class
    ' The example displays the following output:
    '    Unhandled Exception: 
    '       System.NullReferenceException: Object reference not set to an instance of an object.
    '       at Example.Main()
    

    Se produce la excepción porque pages.CurrentPage devuelve null si no hay información de página almacenada en la memoria caché. Esta excepción se puede corregir probando el valor de la CurrentPage propiedad antes de recuperar la propiedad del Title objeto actualPage, como hace el ejemplo siguiente:

    var pages = new Pages();
    Page current = pages.CurrentPage;
    if (current != null)
    {
        string title = current.Title;
        Console.WriteLine($"Current title: '{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.
    
    let pages = Pages()
    let current = pages.CurrentPage
    if box current <> null then
        let title = current.Title
        printfn $"Current title: '{title}'"
    else
        printfn "There is no page information in the cache."
    // The example displays the following output:
    //       There is no page information in the cache.
    
    Module Example
       Public Sub Main()
          Dim pages As New Pages()
          Dim current As Page = pages.CurrentPage
          If current IsNot Nothing Then 
             Dim title As String = current.Title
             Console.WriteLine("Current title: '{0}'", title)
          Else
             Console.WriteLine("There is no page information in the cache.")
          End If   
       End Sub
    End Module
    ' The example displays the following output:
    '       There is no page information in the cache.
    
  • Está enumerando los elementos de una matriz que contiene tipos de referencia y el intento de procesar uno de los elementos produce una NullReferenceException excepción.

    En el ejemplo siguiente se define una matriz de cadenas. Una for instrucción enumera los elementos de la matriz y llama al método de Trim cada cadena antes de mostrar la cadena.

    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.
    
    open System
    
    let values = [| "one"; null; "two" |]
    for i = 0 to values.GetUpperBound 0 do
        printfn $"""{values[i].Trim()}{if i = values.GetUpperBound 0 then "" else ", "}"""
    printfn ""
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.main()
    
    Module Example
       Public Sub Main()
          Dim values() As String = { "one", Nothing, "two" }
          For ctr As Integer = 0 To values.GetUpperBound(0)
             Console.Write("{0}{1}", values(ctr).Trim(), 
                           If(ctr = values.GetUpperBound(0), "", ", ")) 
          Next
          Console.WriteLine()
       End Sub
    End Module
    ' The example displays the following output:
    '    Unhandled Exception: System.NullReferenceException: 
    '       Object reference not set to an instance of an object.
    '       at Example.Main()
    

    Esta excepción se produce si se supone que cada elemento de la matriz debe contener un valor distinto de null y el valor del elemento de matriz es de hecho null. La excepción se puede eliminar mediante la prueba de si el elemento es null antes de realizar cualquier operación en ese elemento, como se muestra en el ejemplo siguiente.

    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
    
    open System
    
    let values = [| "one"; null; "two" |]
    for i = 0 to values.GetUpperBound 0 do
        printf $"""{if values[i] <> null then values[i].Trim() else ""}{if i = values.GetUpperBound 0 then "" else ", "}"""
    Console.WriteLine()
    // The example displays the following output:
    //       one, , two
    
    Module Example
       Public Sub Main()
          Dim values() As String = { "one", Nothing, "two" }
          For ctr As Integer = 0 To values.GetUpperBound(0)
             Console.Write("{0}{1}", 
                           If(values(ctr) IsNot Nothing, values(ctr).Trim(), ""), 
                           If(ctr = values.GetUpperBound(0), "", ", ")) 
          Next
          Console.WriteLine()
       End Sub
    End Module
    ' The example displays the following output:
    '       one, , two
    
  • Método cuando accede a un miembro de uno de sus argumentos, pero ese argumento es null. El PopulateNames método del ejemplo siguiente produce la excepción en la línea names.Add(arrName);.

    using System.Collections.Generic;
    
    public class NRE2Example
    {
        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 (string 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 NRE2Example.PopulateNames(List`1 names)
    //       at NRE2Example.Main()
    
    let populateNames (names: ResizeArray<string>) =
        let arrNames =
            [ "Dakota"; "Samuel"; "Nikita"
              "Koani"; "Saya"; "Yiska"; "Yumaevsky" ]
        for arrName in arrNames do
            names.Add arrName
    
    let getData () : ResizeArray<string> =
        null
    
    let names = getData ()
    populateNames names
    
    // 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 <StartupCode$fs>.main()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As List(Of String) = GetData()
          PopulateNames(names)
       End Sub
       
       Private Sub PopulateNames(names As List(Of String))
          Dim arrNames() As String = { "Dakota", "Samuel", "Nikita",
                                       "Koani", "Saya", "Yiska", "Yumaevsky" }
          For Each arrName In arrNames
             names.Add(arrName)
          Next
       End Sub
       
       Private Function GetData() As List(Of String)
          Return Nothing   
       End Function
    End Module
    ' 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()
    

    Para solucionar este problema, asegúrese de que el argumento pasado al método no nulles o controle la excepción iniciada en un try…catch…finally bloque. Para obtener más información, consulte Excepciones.

  • Se crea una lista sin conocer el tipo y no se inicializó la lista. El GetList método del ejemplo siguiente produce la excepción en la línea emptyList.Add(value).

    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Runtime.Serialization;
    
    public class NullReferenceExample
    {
        public static void Main()
        {
            var listType = GetListType();
            _ = GetList(listType);
        }
    
        private static Type GetListType()
        {
            return typeof(List<int>);
        }
    
        private static IList GetList(Type type)
        {
            var emptyList = (IList)FormatterServices.GetUninitializedObject(type); // Does not call list constructor
            var value = 1;
            emptyList.Add(value);
            return emptyList;
        }
    }
    // The example displays output like the following:
    //    Unhandled Exception: System.NullReferenceException: 'Object reference
    //    not set to an instance of an object.'
    //    at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item)
    //    at NullReferenceExample.GetList(Type type): line 24
    

    Para solucionar este problema, asegúrese de que la lista se inicializa (una manera de hacerlo es llamar Activator.CreateInstance a en lugar de FormatterServices.GetUninitializedObject) o controlar la excepción iniciada en un try…catch…finally bloque. Para obtener más información, consulte Excepciones.

Las siguientes instrucciones de lenguaje intermedio (MSIL) Microsoft inician NullReferenceException: callvirt, cpblk, cpobj, initblk, ldelem.<type>, ldelema, ldfld, ldflda, ldind.<type>, ldlen, stelem.<type>, stfld, stind.<type>, throw y unbox.

NullReferenceException usa HRESULT COR_E_NULLREFERENCE, que tiene el valor 0x80004003.

Para obtener una lista de valores de propiedad iniciales para una instancia de NullReferenceException, vea los NullReferenceException constructores.

Cuándo controlar las excepciones NullReferenceException

Normalmente es mejor evitar una excepción NullReferenceException que controlarla después de que se produzca. Controlar una excepción puede hacer que el código sea más difícil de mantener y comprender, y a veces puede introducir otros errores. Una excepción NullReferenceException suele ser un error no recuperable. En estos casos, permitir que la excepción detenga la aplicación podría ser la mejor alternativa.

Sin embargo, hay muchas situaciones en las que el control del error puede ser útil:

  • La aplicación puede omitir los objetos que son NULL. Por ejemplo, si la aplicación recupera y procesa registros en una base de datos, es posible que pueda omitir algún número de registros incorrectos que dan lugar a objetos NULL. Grabar los datos incorrectos en un archivo de registro o en la interfaz de usuario de la aplicación puede ser todo lo que tiene que hacer.

  • Puede recuperarse de la excepción. Por ejemplo, una llamada a un servicio web que devuelve un tipo de referencia podría devolver null si se pierde la conexión o se agota el tiempo de espera de la conexión. Puede intentar restablecer la conexión e intentar la llamada de nuevo.

  • Puede restaurar el estado de la aplicación a un estado válido. Por ejemplo, podría realizar una tarea de varios pasos que requiere guardar información en un almacén de datos antes de llamar a un método que produce una excepción NullReferenceException. Si el objeto sin inicializar dañaría el registro de datos, puede quitar los datos anteriores antes de cerrar la aplicación.

  • Quiere notificar la excepción. Por ejemplo, si el error se debe a un error del usuario de la aplicación, puede generar un mensaje para ayudarles a proporcionar la información correcta. También puede registrar información sobre el error para ayudarle a solucionar el problema. Algunos marcos, como ASP.NET, tienen un controlador de excepciones de alto nivel que captura todos los errores a que la aplicación nunca se bloquea; en ese caso, registrar la excepción podría ser la única manera en que se puede saber que se produce.

Constructores

Nombre Description
NullReferenceException()

Inicializa una nueva instancia de la NullReferenceException clase , estableciendo la Message propiedad de la nueva instancia en un mensaje proporcionado por el sistema que describe el error, como "Se encontró el valor 'null' donde se requería una instancia de un objeto". Este mensaje tiene en cuenta la referencia cultural del sistema actual.

NullReferenceException(SerializationInfo, StreamingContext)
Obsoletos.

Inicializa una nueva instancia de la NullReferenceException clase con datos serializados.

NullReferenceException(String, Exception)

Inicializa una nueva instancia de la NullReferenceException clase con un mensaje de error especificado y una referencia a la excepción interna que es la causa de esta excepción.

NullReferenceException(String)

Inicializa una nueva instancia de la NullReferenceException clase con un mensaje de error especificado.

Propiedades

Nombre Description
Data

Obtiene una colección de pares clave-valor que proporcionan información adicional definida por el usuario sobre la excepción.

(Heredado de Exception)
HelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.

(Heredado de Exception)
HResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.

(Heredado de Exception)
InnerException

Obtiene la Exception instancia que provocó la excepción actual.

(Heredado de Exception)
Message

Obtiene un mensaje que describe la excepción actual.

(Heredado de Exception)
Source

Obtiene o establece el nombre de la aplicación o el objeto que provoca el error.

(Heredado de Exception)
StackTrace

Obtiene una representación de cadena de los fotogramas inmediatos en la pila de llamadas.

(Heredado de Exception)
TargetSite

Obtiene el método que produce la excepción actual.

(Heredado de Exception)

Métodos

Nombre Description
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetBaseException()

Cuando se reemplaza en una clase derivada, devuelve la Exception causa principal de una o varias excepciones posteriores.

(Heredado de Exception)
GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Cuando se reemplaza en una clase derivada, establece con SerializationInfo información sobre la excepción.

(Heredado de Exception)
GetType()

Obtiene el tipo de tiempo de ejecución de la instancia actual.

(Heredado de Exception)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Crea y devuelve una representación de cadena de la excepción actual.

(Heredado de Exception)

Eventos

Nombre Description
SerializeObjectState
Obsoletos.

Se produce cuando se serializa una excepción para crear un objeto de estado de excepción que contiene datos serializados sobre la excepción.

(Heredado de Exception)

Se aplica a

Consulte también