¿Qué es una NullReferenceException y cómo la soluciono?

Tengo un código y cuando se ejecuta, arroja una NullReferenceException , diciendo:

Referencia a objeto no establecida como instancia de un objeto.

¿Qué significa esto y qué puedo hacer para corregir este error?

¿Cual es la causa?

Línea de fondo

Está intentando usar algo que es null (o Nothing en VB.NET). Esto significa que lo estableces en null o nunca lo configuras para nada.

Como cualquier otra cosa, null se pasa. Si es null en el método “A”, podría ser que el método “B” pasó un null al método “A”.

null puede tener diferentes significados:

  1. Variables de objeto que no están inicializadas y, por lo tanto, apuntan a nada. En este caso, si accede a propiedades o métodos de tales objetos, causa una NullReferenceException .
  2. El desarrollador está usando null intencionalmente para indicar que no hay un valor significativo disponible. Tenga en cuenta que C # tiene el concepto de tipos de datos anulables para variables (como las tablas de base de datos pueden tener campos anulables) – puede asignarle un null para indicar que no hay ningún valor almacenado en él, por ejemplo, int? a = null; int? a = null; donde el signo de interrogación indica que está permitido almacenar nulo en la variable a . Puede verificarlo con if (a.HasValue) {...} o con if (a==null) {...} . Las variables anulables, como a este ejemplo, permiten acceder al valor a través de a.Value explícitamente, o de forma normal a través de a .
    Tenga en cuenta que acceder a él a través de a.Value arroja una InvalidOperationException lugar de una NullReferenceException si a es null ; debe hacer la comprobación de antemano, es decir, si tiene otra variable en nulo variable int b; entonces deberías hacer asignaciones como if (a.HasValue) { b = a.Value; } if (a.HasValue) { b = a.Value; } o más corto if (a != null) { b = a; } if (a != null) { b = a; } .

El rest de este artículo entra en más detalles y muestra los errores que muchos progtwigdores a menudo hacen que pueden conducir a una NullReferenceException .

Más específicamente

El tiempo de ejecución arrojando una NullReferenceException siempre significa lo mismo: está tratando de usar una referencia, y la referencia no se inicializa (o se inicializó una vez , pero ya no se inicializa).

Esto significa que la referencia es null y no puede acceder a los miembros (como los métodos) a través de una referencia null . El caso más simple:

 string foo = null; foo.ToUpper(); 

Esto arrojará una NullReferenceException en la segunda línea porque no puede llamar al método de instancia ToUpper() en una referencia de string apuntando a null .

Depuración

¿Cómo se encuentra la fuente de una NullReferenceException ? Además de observar la excepción en sí misma, que será lanzada exactamente en el lugar donde ocurre, se aplican las reglas generales de depuración en Visual Studio: coloque puntos de corte estratégicos e inspeccione sus variables , colocando el mouse sobre sus nombres, abriendo un ( Rápido) Mire la ventana o use los diversos paneles de depuración como Locals y Autos.

Si desea saber dónde está o no está establecida la referencia, haga clic derecho en su nombre y seleccione “Buscar todas las referencias”. A continuación, puede colocar un punto de interrupción en cada ubicación encontrada y ejecutar su progtwig con el depurador conectado. Cada vez que el depurador se rompe en un punto de interrupción así, debe determinar si espera que la referencia sea no nula, inspeccionar la variable y verificar que apunta a una instancia cuando lo espera.

Al seguir el flujo del progtwig de esta manera, puede encontrar la ubicación donde la instancia no debe ser nula y por qué no está configurada correctamente.

Ejemplos

Algunos escenarios comunes donde se puede lanzar la excepción:

Genérico

 ref1.ref2.ref3.member 

Si ref1 o ref2 o ref3 son nulos, entonces obtendrás una NullReferenceException . Si quiere resolver el problema, descubra cuál es nulo reescribiendo la expresión en su equivalente más simple:

 var r1 = ref1; var r2 = r1.ref2; var r3 = r2.ref3; r3.member 

Específicamente, en HttpContext.Current.User.Identity.Name , HttpContext.Current podría ser nulo, o la propiedad User podría ser nula, o la propiedad Identity podría ser nula.

Indirecto

 public class Person { public int Age { get; set; } } public class Book { public Person Author { get; set; } } public class Example { public void Foo() { Book b1 = new Book(); int authorAge = b1.Author.Age; // You never initialized the Author property. // there is no Person to get an Age from. } } 

Si desea evitar la referencia nula secundaria (Persona), puede inicializarla en el constructor del objeto principal (Libro).

Inicializadores de objetos nesteds

Lo mismo se aplica a los inicializadores de objetos nesteds:

 Book b1 = new Book { Author = { Age = 45 } }; 

Esto se traduce a

 Book b1 = new Book(); b1.Author.Age = 45; 

Mientras se utiliza la new palabra clave, solo crea una nueva instancia de Book , pero no una nueva instancia de Person , por lo que el Author la propiedad sigue siendo null .

Inicializadores de colecciones anidadas

 public class Person { public ICollection Books { get; set; } } public class Book { public string Title { get; set; } } 

Los inicializadores de colección nesteds se comportan de la misma manera:

 Person p1 = new Person { Books = { new Book { Title = "Title1" }, new Book { Title = "Title2" }, } }; 

Esto se traduce a

 Person p1 = new Person(); p1.Books.Add(new Book { Title = "Title1" }); p1.Books.Add(new Book { Title = "Title2" }); 

La new Person solo crea una instancia de Person , pero la colección Books sigue siendo null . La syntax del inicializador de la colección no crea una colección para p1.Books , solo se traduce a las p1.Books.Add(...) .

Formación

 int[] numbers = null; int n = numbers[0]; // numbers is null. There is no array to index. 

Array Elements

 Person[] people = new Person[5]; people[0].Age = 20 // people[0] is null. The array was allocated but not // initialized. There is no Person to set the Age for. 

Arrays dentados

 long[][] array = new long[1][]; array[0][0] = 3; // is null because only the first dimension is yet initialized. // Use array[0] = new long[2]; first. 

Colección / Lista / Diccionario

 Dictionary agesForNames = null; int age = agesForNames["Bob"]; // agesForNames is null. // There is no Dictionary to perform the lookup. 

Variable de Rango (Indirecta / Deferida)

 public class Person { public string Name { get; set; } } var people = new List(); people.Add(null); var names = from p in people select p.Name; string firstName = names.First(); // Exception is thrown here, but actually occurs // on the line above. "p" is null because the // first element we added to the list is null. 

Eventos

 public class Demo { public event EventHandler StateChanged; protected virtual void OnStateChanged(EventArgs e) { StateChanged(this, e); // Exception is thrown here // if no event handlers have been attached // to StateChanged event } } 

Convenciones de mal nombre:

Si nombraste los campos de forma diferente a los locales, te habrás dado cuenta de que nunca has inicializado el campo.

 public class Form1 { private Customer customer; private void Form1_Load(object sender, EventArgs e) { Customer customer = new Customer(); customer.Name = "John"; } private void Button_Click(object sender, EventArgs e) { MessageBox.Show(customer.Name); } } 

Esto puede resolverse siguiendo la convención para prefijar campos con un guión bajo:

 private Customer _customer; 

Ciclo de vida de la página ASP.NET:

 public partial class Issues_Edit : System.Web.UI.Page { protected TestIssue myIssue; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Only called on first load, not when button clicked myIssue = new TestIssue(); } } protected void SaveButton_Click(object sender, EventArgs e) { myIssue.Entry = "NullReferenceException here!"; } } 

Valores de sesión de ASP.NET

 // if the "FirstName" session value has not yet been set, // then this line will throw a NullReferenceException string firstName = Session["FirstName"].ToString(); 

Modelos de vista vacía ASP.NET MVC

Si se produce la excepción al hacer referencia a una propiedad de @Model en una vista MVC de ASP.NET, debe comprender que el Model se establece en su método de acción cuando return una vista. Cuando devuelve un modelo vacío (o propiedad del modelo) desde su controlador, la excepción se produce cuando las vistas acceden a él:

 // Controller public class Restaurant:Controller { public ActionResult Search() { return View(); // Forgot the provide a Model here. } } // Razor view @foreach (var restaurantSearch in Model.RestaurantSearch) // Throws. { } 

@Model.somePropertyName

Orden de creación de control de WPF y eventos

Los controles WPF se crean durante la llamada a InitializeComponent en el orden en que aparecen en el árbol visual. Se generará una NullReferenceException en el caso de los controles creados con anticipación con controladores de eventos, etc., que se activan durante InitializeComponent que hace referencia a controles creados más tarde.

Por ejemplo :

           

Aquí comboBox1 se crea antes de label1 . Si comboBox1_SelectionChanged intenta hacer referencia a `label1, aún no se habrá creado.

 private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!! } 

Cambiar el orden de las declaraciones en el XAML (es decir, listar label1 antes de comboBox1 , ignorar los problemas de filosofía de diseño, al menos resolvería la NullReferenceException aquí.

Reparto con as

 var myThing = someObject as Thing; 

Esto no arroja una InvalidCastException, pero devuelve un null cuando el molde falla (y cuando someObject es nulo). Así que ten cuidado de eso.

LINQ FirstOrDefault () y SingleOrDefault ()

Las versiones simples First() y Single() arrojan excepciones cuando no hay nada. Las versiones “OrDefault” devuelven nulo en ese caso. Así que ten cuidado de eso.

para cada

foreach lanza cuando intenta iterar colección nula. Generalmente causado por un resultado null inesperado de métodos que devuelven colecciones.

  List list = null; foreach(var v in list) { } // exception 

Ejemplo más realista: seleccione nodos del documento XML. Lanzará si no se encuentran los nodos pero la depuración inicial muestra que todas las propiedades son válidas:

  foreach (var node in myData.MyXml.DocumentNode.SelectNodes("//Data")) 

Formas de evitar

Compruebe explícitamente null e ignore los valores nulos.

Si espera que la referencia a veces sea nula, puede verificar que sea null antes de acceder a los miembros de la instancia:

 void PrintName(Person p) { if (p != null) { Console.WriteLine(p.Name); } } 

Verifica explícitamente null y proporciona un valor predeterminado.

Los métodos llamados que espera devolver una instancia pueden devolver null , por ejemplo, cuando no se puede encontrar el objeto que se busca. Puede optar por devolver un valor predeterminado cuando este sea el caso:

 string GetCategory(Book b) { if (b == null) return "Unknown"; return b.Category; } 

Verifica explícitamente null de las llamadas al método y lanza una excepción personalizada.

También puede lanzar una excepción personalizada, solo para capturarla en el código de llamada:

 string GetCategory(string bookTitle) { var book = library.FindBook(bookTitle); // This may return null if (book == null) throw new BookNotFoundException(bookTitle); // Your custom exception return book.Category; } 

Use Debug.Assert si un valor nunca debe ser null , para detectar el problema antes de que ocurra la excepción.

Cuando sepa durante el desarrollo que un método puede, pero nunca debe devolver null , puede usar Debug.Assert() para romper lo antes posible cuando ocurra:

 string GetTitle(int knownBookID) { // You know this should never return null. var book = library.GetBook(knownBookID); // Exception will occur on the next line instead of at the end of this method. Debug.Assert(book != null, "Library didn't return a book for known book ID."); // Some other code return book.Title; // Will never throw NullReferenceException in Debug mode. } 

Aunque esta comprobación no terminará en su comstackción de lanzamiento , haciendo que arroje la NullReferenceException nuevamente cuando book == null en tiempo de ejecución en modo de lanzamiento.

Use GetValueOrDefault() para los tipos de valores que aceptan valores NULL para proporcionar un valor predeterminado cuando son null .

 DateTime? appointment = null; Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now)); // Will display the default value provided (DateTime.Now), because appointment is null. appointment = new DateTime(2022, 10, 20); Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now)); // Will display the appointment date, not the default 

Use el operador nulo coalescente: ?? [C #] o If() [VB].

La abreviatura de proporcionar un valor predeterminado cuando se encuentra un null :

 IService CreateService(ILogger log, Int32? frobPowerLevel) { var serviceImpl = new MyService(log ?? NullLog.Instance); // Note that the above "GetValueOrDefault()" can also be rewritten to use // the coalesce operator: serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5; } 

Use el operador de condición nula: ?. o ?[x] para matrices (disponible en C # 6 y VB.NET 14):

Esto también se llama a veces la navegación segura o el operador de Elvis (después de su forma). Si la expresión en el lado izquierdo del operador es nula, entonces no se evaluará el lado derecho y se devolverá el valor nulo. Eso significa casos como este:

 var title = person.Title.ToUpper(); 

Si la persona no tiene un título, lanzará una excepción porque intenta llamar a ToUpper en una propiedad con un valor nulo.

En C # 5 y abajo, esto puede protegerse con:

 var title = person.Title == null ? null : person.Title.ToUpper(); 

Ahora la variable de título será nula en lugar de arrojar una excepción. C # 6 introduce una syntax más corta para esto:

 var title = person.Title?.ToUpper(); 

Esto dará como resultado que la variable de título sea null y la llamada a ToUpper no se realice si person.Title es null .

Por supuesto, aún debe verificar el title para nulo o usar el operador de condición nula junto con el operador nulo coalescente ( ?? ) para proporcionar un valor predeterminado:

 // regular null check int titleLength = 0; if (title != null) titleLength = title.Length; // If title is null, this would throw NullReferenceException // combining the `?` and the `??` operator int titleLength = title?.Length ?? 0; 

Del mismo modo, para las matrices que puede utilizar ?[i] siguiente manera:

 int[] myIntArray=null; var i=5; int? elem = myIntArray?[i]; if (!elem.HasValue) Console.WriteLine("No value"); 

Esto hará lo siguiente: Si myIntArray es nulo, la expresión devuelve nulo y puede verificarlo de manera segura. Si contiene una matriz, hará lo mismo que: elem = myIntArray[i]; y devuelve el elemento i- ésimo .

Técnicas especiales para la depuración y corrección de derefs nulos en iteradores

C # admite “bloques iteradores” (llamados “generadores” en algunos otros lenguajes populares). Las excepciones de eliminación de referencias nulas pueden ser particularmente difíciles de depurar en bloques de iteradores debido a la ejecución diferida:

 public IEnumerable GetFrobs(FrobFactory f, int count) { for (int i = 0; i < count; ++i) yield return f.MakeFrob(); } ... FrobFactory factory = whatever; IEnumerable frobs = GetFrobs(); ... foreach(Frob frob in frobs) { ... } 

Si whatever resulta en null entonces MakeFrob lanzará. Ahora, podrías pensar que lo correcto es esto:

 // DON'T DO THIS public IEnumerable GetFrobs(FrobFactory f, int count) { if (f == null) throw new ArgumentNullException("f", "factory must not be null"); for (int i = 0; i < count; ++i) yield return f.MakeFrob(); } 

¿Por qué está mal? Porque el bloque iterador no se ejecuta hasta el foreach . La llamada a GetFrobs simplemente devuelve un objeto que cuando se itera ejecutará el bloque iterador.

Al escribir un cheque nulo como este, evita la desreferencia nula, pero mueve la excepción del argumento nulo al punto de la iteración , no al punto de la llamada , y eso es muy confuso de depurar .

La solución correcta es:

 // DO THIS public IEnumerable GetFrobs(FrobFactory f, int count) { // No yields in a public method that throws! if (f == null) throw new ArgumentNullException("f", "factory must not be null"); return GetFrobsForReal(f, count); } private IEnumerable GetFrobsForReal(FrobFactory f, int count) { // Yields in a private method Debug.Assert(f != null); for (int i = 0; i < count; ++i) yield return f.MakeFrob(); } 

Es decir, crea un método de ayuda privada que tiene la lógica de bloques del iterador y un método de superficie pública que realiza la comprobación nula y devuelve el iterador. Ahora cuando se llama a GetFrobs , la verificación nula ocurre inmediatamente, y luego GetFrobsForReal ejecuta cuando se itera la secuencia.

Si examina la fuente de referencia para LINQ to Objects, verá que esta técnica se utiliza en todo momento. Escribir es algo más torpe, pero hace que los errores de nulidad en la depuración sean mucho más fáciles. Optimice su código para la comodidad de la persona que llama, no la conveniencia del autor .

Una nota sobre desreferencias nulas en código inseguro

C # tiene un modo "inseguro" que, como su nombre lo indica, es extremadamente peligroso porque no se aplican los mecanismos de seguridad normales que proporcionan seguridad de memoria y seguridad tipo. No debería escribir código inseguro a menos que tenga una comprensión profunda y profunda de cómo funciona la memoria .

En modo inseguro, debe tener en cuenta dos hechos importantes:

  • desreferenciar un puntero nulo produce la misma excepción que desreferenciar una referencia nula
  • Desreferenciar un puntero no nulo no válido puede producir esa excepción en algunas circunstancias

Para entender por qué es así, es útil comprender cómo .NET produce excepciones de eliminación de referencias nulas en primer lugar. (Estos detalles se aplican a .NET que se ejecuta en Windows; otros sistemas operativos usan mecanismos similares).

La memoria está virtualizada en Windows; cada proceso obtiene un espacio de memoria virtual de muchas "páginas" de memoria que son rastreadas por el sistema operativo. Cada página de memoria tiene banderas establecidas que determinan cómo se puede usar: leer desde, escribir en, ejecutar, etc. La página más baja está marcada como "produce un error si alguna vez se utiliza de alguna manera".

Tanto un puntero nulo como una referencia nula en C # se representan internamente como el número cero, por lo que cualquier bash de desreferenciarlo en su correspondiente almacenamiento de memoria hace que el sistema operativo produzca un error. El tiempo de ejecución .NET luego detecta este error y lo convierte en la excepción de eliminación de referencias nula.

Es por eso que desreferenciar tanto un puntero nulo como una referencia nula produce la misma excepción.

¿Qué hay del segundo punto? La desreferenciación de cualquier puntero no válido que se encuentre en la página más baja de la memoria virtual provoca el mismo error del sistema operativo y, por lo tanto, la misma excepción.

¿Por qué esto tiene sentido? Bueno, supongamos que tenemos una estructura que contiene dos entradas, y un puntero no administrado igual a nulo. Si intentamos eliminar la referencia del segundo int en la estructura, el CLR no intentará acceder al almacenamiento en la ubicación cero; accederá al almacenamiento en la ubicación cuatro. Pero lógicamente esto es una desreferencia nula porque estamos llegando a esa dirección a través del nulo.

Si está trabajando con un código inseguro y obtiene una excepción de eliminación de referencias nula, tenga en cuenta que el puntero infractor no necesita ser nulo. Puede ser cualquier ubicación en la página más baja y esta excepción se producirá.

Excepción de NullReference: Visual Basic

La NullReference Exception para Visual Basic no es diferente de la de C # . Después de todo, ambos informan la misma excepción definida en .NET Framework que ambos usan. Causas únicas de Visual Basic son raras (quizás solo una).

Esta respuesta utilizará términos, syntax y contexto de Visual Basic. Los ejemplos utilizados provienen de una gran cantidad de preguntas anteriores sobre desbordamiento de stack. Esto es para maximizar la relevancia mediante el uso de los tipos de situaciones que a menudo se ven en las publicaciones. También se proporciona una explicación un poco más para aquellos que puedan necesitarla. Es muy probable que se incluya aquí un ejemplo similar al suyo.

Nota:

  1. Esto está basado en conceptos: no hay un código para pegar en su proyecto. Su objective es ayudarlo a comprender qué causa una NullReferenceException (NRE), cómo encontrarla, cómo solucionarla y cómo evitarla. Un NRE puede ser causado de muchas maneras, por lo que es poco probable que sea su único encuentro.
  2. Los ejemplos (de las publicaciones de Stack Overflow) no siempre muestran la mejor manera de hacer algo en primer lugar.
  3. Por lo general, se usa el remedio más simple.

Significado Básico

El mensaje “Objeto no configurado en una instancia de Objeto” significa que está intentando utilizar un objeto que no se ha inicializado. Esto se reduce a uno de estos:

  • Su código declaró una variable de objeto, pero no la inicializó (crear una instancia o ‘ instanciarla ‘)
  • Algo que su código asumió que inicializaría un objeto, no lo hizo
  • Posiblemente, otro código invalidó prematuramente un objeto que aún está en uso

Encontrar la causa

Como el problema es una referencia de objeto que es Nothing , la respuesta es examinarlos para descubrir cuál. Luego determine por qué no se inicializa. Mantenga el mouse sobre las diversas variables y Visual Studio (VS) mostrará sus valores; el culpable será Nothing .

Pantalla de depuración IDE

También debe eliminar cualquier bloque Try / Catch del código relevante, especialmente aquellos donde no hay nada en el bloque Catch. Esto hará que su código se cuelgue cuando intente usar un objeto que sea Nothing . Esto es lo que quiere porque identificará la ubicación exacta del problema y le permitirá identificar el objeto que lo causa.

Una MsgBox en la captura que muestra un Error while... será de poca ayuda. Este método también genera muy malas preguntas sobre el desbordamiento de stack, porque no se puede describir la excepción real, el objeto involucrado o incluso la línea de código donde ocurre.

También puede usar la Locals Window ( Depurar -> Windows -> Locales ) para examinar sus objetos.

Una vez que sepa qué y dónde está el problema, generalmente es bastante fácil de arreglar y más rápido que publicar una nueva pregunta.

Ver también:

  • Puntos de ruptura
  • MSDN: Cómo: Usar el bloque de prueba / captura para detectar excepciones
  • MSDN: mejores prácticas para excepciones

Ejemplos y remedios

Objetos de clase / Crear una instancia

 Dim reg As CashRegister ... TextBox1.Text = reg.Amount ' NRE 

El problema es que Dim no crea un objeto CashRegister; solo declara una variable llamada reg de ese tipo. Declarar una variable de objeto y crear una instancia son dos cosas diferentes.

Remedio

El operador New menudo se puede utilizar para crear la instancia cuando la declara:

 Dim reg As New CashRegister ' [New] creates instance, invokes the constructor ' Longer, more explicit form: Dim reg As CashRegister = New CashRegister 

Cuando solo es apropiado crear la instancia más adelante:

 Private reg As CashRegister ' Declare ... reg = New CashRegister() ' Create instance 

Nota: No use Dim nuevamente en un procedimiento, incluido el constructor ( Sub New ):

 Private reg As CashRegister '... Public Sub New() '... Dim reg As New CashRegister End Sub 

Esto creará una variable local , reg , que existe solo en ese contexto (sub). La variable reg con el Scope nivel de módulo que Scope todos lados permanece Nothing .

La ausencia del operador New es la causa n. ° 1 de las NullReference Exceptions de NullReference Exceptions observadas en las preguntas sobre desbordamiento de stack revisadas.

Visual Basic intenta borrar el proceso repetidamente usando New : Using the New Operator crea un nuevo objeto y llama a Sub New , el constructor, donde su objeto puede realizar cualquier otra inicialización.

Para ser claros, Dim (o Private ) solo declara una variable y su Type . El scope de la variable, ya sea que exista para todo el módulo / clase o sea local para un procedimiento, está determinada por el lugar donde se declara. Private | Friend | Public Private | Friend | Public define el nivel de acceso, no el scope .

Para más información, ver:

  • Nuevo operador
  • Alcance en Visual Basic
  • Niveles de acceso en Visual Basic
  • Tipos de valores y tipos de referencia

Arrays

Las matrices también deben ser instanciadas:

 Private arr as String() 

Esta matriz solo ha sido declarada, no creada. Hay varias formas de inicializar una matriz:

 Private arr as String() = New String(10){} ' or Private arr() As String = New String(10){} ' For a local array (in a procedure) and using 'Option Infer': Dim arr = New String(10) {} 

Nota: A partir de VS 2010, al inicializar una matriz local utilizando un literal y Option Infer , los elementos As y New son opcionales:

 Dim myDbl As Double() = {1.5, 2, 9.9, 18, 3.14} Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14} Dim myDbl() = {1.5, 2, 9.9, 18, 3.14} 

El tipo de datos y el tamaño de la matriz se deducen de los datos que se asignan. Las declaraciones de nivel de clase / módulo aún requieren As con Option Strict :

 Private myDoubles As Double() = {1.5, 2, 9.9, 18, 3.14} 

Ejemplo: matriz de objetos de clase

 Dim arrFoo(5) As Foo For i As Integer = 0 To arrFoo.Count - 1 arrFoo(i).Bar = i * 10 ' Exception Next 

La matriz ha sido creada, pero los objetos de Foo en ella no.

Remedio

 For i As Integer = 0 To arrFoo.Count - 1 arrFoo(i) = New Foo() ' Create Foo instance arrFoo(i).Bar = i * 10 Next 

Usar una List(Of T) hará que sea bastante difícil tener un elemento sin un objeto válido:

 Dim FooList As New List(Of Foo) ' List created, but it is empty Dim f As Foo ' Temporary variable for the loop For i As Integer = 0 To 5 f = New Foo() ' Foo instance created f.Bar = i * 10 FooList.Add(f) ' Foo object added to list Next 

Para más información, ver:

  • Declaración Inferible de Opción
  • Alcance en Visual Basic
  • Arrays en Visual Basic

Listas y colecciones

Las colecciones .NET (de las cuales hay muchas variedades – Listas, Diccionario, etc.) también se deben crear instancias o crear instancias.

 Private myList As List(Of String) .. myList.Add("ziggy") ' NullReference 

Obtiene la misma excepción por la misma razón: myList solo se declaró, pero no se creó ninguna instancia. El remedio es el mismo:

 myList = New List(Of String) ' Or create an instance when declared: Private myList As New List(Of String) 

Un descuido común es una clase que usa un Type colección:

 Public Class Foo Private barList As List(Of Bar) Friend Function BarCount As Integer Return barList.Count End Function Friend Sub AddItem(newBar As Bar) If barList.Contains(newBar) = False Then barList.Add(newBar) End If End Function 

Cualquiera de los dos procedimientos dará como resultado un NRE, ya que barList solo se declara, no se barList una instancia. La creación de una instancia de Foo tampoco creará una instancia de barList interna. Pudo haber sido la intención de hacer esto en el constructor:

 Public Sub New ' Constructor ' Stuff to do when a new Foo is created... barList = New List(Of Bar) End Sub 

Como antes, esto es incorrecto:

 Public Sub New() ' Creates another barList local to this procedure Dim barList As New List(Of Bar) End Sub 

Para obtener más información, vea List(Of T) Class .


Objetos del proveedor de datos

Trabajar con bases de datos presenta muchas oportunidades para una NullReference porque puede haber muchos objetos ( Command , Connection , Transaction , Dataset , DataTable , DataRows ….) en uso a la vez. Nota: No importa qué proveedor de datos esté utilizando: MySQL, SQL Server, OleDB, etc., los conceptos son los mismos.

Ejemplo 1

 Dim da As OleDbDataAdapter Dim ds As DataSet Dim MaxRows As Integer con.Open() Dim sql = "SELECT * FROM tblfoobar_List" da = New OleDbDataAdapter(sql, con) da.Fill(ds, "foobar") con.Close() MaxRows = ds.Tables("foobar").Rows.Count ' Error 

Como antes, se declaró el objeto ds Dataset, pero nunca se creó una instancia. El DataAdapter llenará un DataSet existente, no creará uno. En este caso, dado que ds es una variable local, el IDE le advierte que esto podría suceder:

img

Cuando se declara como una variable de nivel de clase / módulo, como parece ser el caso con con , el comstackdor no puede saber si el objeto fue creado por un procedimiento en sentido ascendente. No ignores las advertencias

Remedio

 Dim ds As New DataSet 

Ejemplo 2

 ds = New DataSet da = New OleDBDataAdapter(sql, con) da.Fill(ds, "Employees") txtID.Text = ds.Tables("Employee").Rows(0).Item(1) txtID.Name = ds.Tables("Employee").Rows(0).Item(2) 

Un error tipográfico es un problema aquí: Employees vs Employee . No se creó DataTable nombre “Empleado”, por lo que se obtiene una NullReferenceException intentar acceder a él. Otro problema potencial es suponer que habrá Items que pueden no serlo cuando el SQL incluye una cláusula WHERE.

Remedio

Dado que esto usa una tabla, usar Tables(0) evitará errores de ortografía. Examinar Rows.Count también puede ayudar:

 If ds.Tables(0).Rows.Count > 0 Then txtID.Text = ds.Tables(0).Rows(0).Item(1) txtID.Name = ds.Tables(0).Rows(0).Item(2) End If 

Fill es una función que devuelve el número de Rows afectadas que también se puede probar:

 If da.Fill(ds, "Employees") > 0 Then... 

Ejemplo 3

 Dim da As New OleDb.OleDbDataAdapter("SELECT TICKET.TICKET_NO, TICKET.CUSTOMER_ID, ... FROM TICKET_RESERVATION AS TICKET INNER JOIN FLIGHT_DETAILS AS FLIGHT ... WHERE [TICKET.TICKET_NO]= ...", con) Dim ds As New DataSet da.Fill(ds) If ds.Tables("TICKET_RESERVATION").Rows.Count > 0 Then 

El DataAdapter proporcionará TableNames como se muestra en el ejemplo anterior, pero no analiza los nombres del SQL o de la tabla de la base de datos. Como resultado, ds.Tables("TICKET_RESERVATION") referencia a una tabla inexistente.

El Remedio es el mismo, haga referencia a la tabla por índice:

 If ds.Tables(0).Rows.Count > 0 Then 

Ver también Clase DataTable .


Rutas de objetos / nesteds

 If myFoo.Bar.Items IsNot Nothing Then ... 

El código solo está probando Items mientras que myFoo y Bar también pueden ser Nothing. El remedio es probar toda la cadena o camino de objetos de uno en uno:

 If (myFoo IsNot Nothing) AndAlso (myFoo.Bar IsNot Nothing) AndAlso (myFoo.Bar.Items IsNot Nothing) Then .... 

AndAlso es importante. Las pruebas subsiguientes no se realizarán una vez que se encuentre la primera condición False . Esto permite que el código ‘perfore’ de forma segura en el / los objeto / s un ‘nivel’ a la vez, evaluando myFoo.Bar solo después de (y si) se determina que myFoo es válido. Las cadenas o rutas de objetos pueden ser bastante largas cuando se codifican objetos complejos:

 myBase.myNodes(3).Layer.SubLayer.Foo.Files.Add("somefilename") 

No es posible hacer referencia a nada ‘aguas abajo’ de un objeto null . Esto también se aplica a los controles:

 myWebBrowser.Document.GetElementById("formfld1").InnerText = "some value" 

Aquí, myWebBrowser o Document podría ser Nothing o el elemento formfld1 puede no existir.


Controles de interfaz de usuario

 Dim cmd5 As New SqlCommand("select Cartons, Pieces, Foobar " _ & "FROM Invoice where invoice_no = '" & _ Me.ComboBox5.SelectedItem.ToString.Trim & "' And category = '" & _ Me.ListBox1.SelectedItem.ToString.Trim & "' And item_name = '" & _ Me.ComboBox2.SelectedValue.ToString.Trim & "' And expiry_date = '" & _ Me.expiry.Text & "'", con) 

Entre otras cosas, este código no anticipa que el usuario no haya seleccionado algo en uno o más controles de UI. ListBox1.SelectedItem bien puede ser Nothing , por lo que ListBox1.SelectedItem.ToString dará como resultado un NRE.

Remedio

Valide los datos antes de usarlos (también use los parámetros Option Strict y SQL):

 Dim expiry As DateTime ' for text date validation If (ComboBox5.SelectedItems.Count > 0) AndAlso (ListBox1.SelectedItems.Count > 0) AndAlso (ComboBox2.SelectedItems.Count > 0) AndAlso (DateTime.TryParse(expiry.Text, expiry) Then '... do stuff Else MessageBox.Show(...error message...) End If 

Alternativamente, puede usar (ComboBox5.SelectedItem IsNot Nothing) AndAlso...


Visual Basic Forms

 Public Class Form1 Private NameBoxes = New TextBox(5) {Controls("TextBox1"), _ Controls("TextBox2"), Controls("TextBox3"), _ Controls("TextBox4"), Controls("TextBox5"), _ Controls("TextBox6")} ' same thing in a different format: Private boxList As New List(Of TextBox) From {TextBox1, TextBox2, TextBox3 ...} ' Immediate NRE: Private somevar As String = Me.Controls("TextBox1").Text 

This is a fairly common way to get an NRE. In C#, depending on how it is coded, the IDE will report that Controls does not exist in the current context, or “cannot reference non-static member”. So, to some extent, this is a VB-only situation. It is also complex because it can result in a failure cascade.

The arrays and collections cannot be initialized this way. This initialization code will run before the constructor creates the Form or the Controls . As a result:

  • Lists and Collection will simply be empty
  • The Array will contain five elements of Nothing
  • The somevar assignment will result in an immediate NRE because Nothing doesn’t have a .Text property

Referencing array elements later will result in an NRE. If you do this in Form_Load , due to an odd bug, the IDE may not report the exception when it happens. The exception will pop up later when your code tries to use the array. This “silent exception” is detailed in this post . For our purposes, the key is that when something catastrophic happens while creating a form ( Sub New or Form Load event), exceptions may go unreported, the code exits the procedure and just displays the form.

Since no other code in your Sub New or Form Load event will run after the NRE, a great many other things can be left uninitialized.

 Sub Form_Load(..._ '... Dim name As String = NameBoxes(2).Text ' NRE ' ... ' More code (which will likely not be executed) ' ... End Sub 

Note this applies to any and all control and component references making these illegal where they are:

 Public Class Form1 Private myFiles() As String = Me.OpenFileDialog1.FileName & ... Private dbcon As String = OpenFileDialog1.FileName & ";Jet Oledb..." Private studentName As String = TextBox13.Text 

Partial Remedy

It is curious that VB does not provide a warning, but the remedy is to declare the containers at the form level, but initialize them in form load event handler when the controls do exist. This can be done in Sub New as long as your code is after the InitializeComponent call:

 ' Module level declaration Private NameBoxes as TextBox() Private studentName As String ' Form Load, Form Shown or Sub New: ' ' Using the OP's approach (illegal using OPTION STRICT) NameBoxes = New TextBox() {Me.Controls("TextBox1"), Me.Controls("TestBox2"), ...) studentName = TextBox32.Text ' For simple control references 

The array code may not be out of the woods yet. Any controls which are in a container control (like a GroupBox or Panel ) will not be found in Me.Controls ; they will be in the Controls collection of that Panel or GroupBox. Nor will a control be returned when the control name is misspelled ( "TeStBox2" ). In such cases, Nothing will again be stored in those array elements and an NRE will result when you attempt to reference it.

These should be easy to find now that you know what you are looking for: VS shows you the error of your ways

“Button2” resides on a Panel

Remedio

Rather than indirect references by name using the form’s Controls collection, use the control reference:

 ' Declaration Private NameBoxes As TextBox() ' Initialization - simple and easy to read, hard to botch: NameBoxes = New TextBox() {TextBox1, TextBox2, ...) ' Initialize a List NamesList = New List(Of TextBox)({TextBox1, TextBox2, TextBox3...}) ' or NamesList = New List(Of TextBox) NamesList.AddRange({TextBox1, TextBox2, TextBox3...}) 

Function Returning Nothing

 Private bars As New List(Of Bars) ' Declared and created Public Function BarList() As List(Of Bars) bars.Clear If someCondition Then For n As Integer = 0 to someValue bars.Add(GetBar(n)) Next n Else Exit Function End If Return bars End Function 

This is a case where the IDE will warn you that ‘ not all paths return a value and a NullReferenceException may result ‘. You can suppress the warning, by replacing Exit Function with Return Nothing , but that does not solve the problem. Anything which tries to use the return when someCondition = False will result in an NRE:

 bList = myFoo.BarList() For Each b As Bar in bList ' EXCEPTION ... 

Remedio

Replace Exit Function in the function with Return bList . Returning an empty List is not the same as returning Nothing . If there is a chance that a returned object can be Nothing , test before using it:

  bList = myFoo.BarList() If bList IsNot Nothing Then... 

Poorly Implemented Try/Catch

A badly implemented Try/Catch can hide where the problem is and result in new ones:

 Dim dr As SqlDataReader Try Dim lnk As LinkButton = TryCast(sender, LinkButton) Dim gr As GridViewRow = DirectCast(lnk.NamingContainer, GridViewRow) Dim eid As String = GridView1.DataKeys(gr.RowIndex).Value.ToString() ViewState("username") = eid sqlQry = "select FirstName, Surname, DepartmentName, ExtensionName, jobTitle, Pager, mailaddress, from employees1 where username='" & eid & "'" If connection.State <> ConnectionState.Open Then connection.Open() End If command = New SqlCommand(sqlQry, connection) 'More code fooing and barring dr = command.ExecuteReader() If dr.Read() Then lblFirstName.Text = Convert.ToString(dr("FirstName")) ... End If mpe.Show() Catch Finally command.Dispose() dr.Close() ' < -- NRE connection.Close() End Try 

This is a case of an object not being created as expected, but also demonstrates the counter usefulness of an empty Catch .

There is an extra comma in the SQL (after 'mailaddress') which results in an exception at .ExecuteReader . After the Catch does nothing, Finally tries to perform clean up, but since you cannot Close a null DataReader object, a brand new NullReferenceException results.

An empty Catch block is the devil's playground. This OP was baffled why he was getting an NRE in the Finally block. In other situations, an empty Catch may result in something else much further downstream going haywire and cause you to spend time looking at the wrong things in the wrong place for the problem. (The "silent exception" described above provides the same entertainment value.)

Remedio

Don't use empty Try/Catch blocks - let the code crash so you can a) identify the cause b) identify the location and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from the person uniquely qualified to fix them - the developer.


DBNull is not the same as Nothing

 For Each row As DataGridViewRow In dgvPlanning.Rows If Not IsDBNull(row.Cells(0).Value) Then ... 

The IsDBNull function is used to test if a value equals System.DBNull : From MSDN:

The System.DBNull value indicates that the Object represents missing or non-existent data. DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized.

Remedio

 If row.Cells(0) IsNot Nothing Then ... 

As before, you can test for Nothing, then for a specific value:

 If (row.Cells(0) IsNot Nothing) AndAlso (IsDBNull(row.Cells(0).Value) = False) Then 

Ejemplo 2

 Dim getFoo = (From f In dbContext.FooBars Where f.something = something Select f).FirstOrDefault If Not IsDBNull(getFoo) Then If IsDBNull(getFoo.user_id) Then txtFirst.Text = getFoo.first_name Else ... 

FirstOrDefault returns the first item or the default value, which is Nothing for reference types and never DBNull :

 If getFoo IsNot Nothing Then... 

Controles

 Dim chk As CheckBox chk = CType(Me.Controls(chkName), CheckBox) If chk.Checked Then Return chk End If 

If a CheckBox with chkName can't be found (or exists in a GroupBox ), then chk will be Nothing and be attempting to reference any property will result in an exception.

Remedio

 If (chk IsNot Nothing) AndAlso (chk.Checked) Then ... 

The DataGridView

The DGV has a few quirks seen periodically:

 dgvBooks.DataSource = loan.Books dgvBooks.Columns("ISBN").Visible = True ' NullReferenceException dgvBooks.Columns("Title").DefaultCellStyle.Format = "C" dgvBooks.Columns("Author").DefaultCellStyle.Format = "C" dgvBooks.Columns("Price").DefaultCellStyle.Format = "C" 

If dgvBooks has AutoGenerateColumns = True , it will create the columns, but it does not name them, so the above code fails when it references them by name.

Remedio

Name the columns manually, or reference by index:

 dgvBooks.Columns(0).Visible = True 

Example 2 — Beware of the NewRow

 xlWorkSheet = xlWorkBook.Sheets("sheet1") For i = 0 To myDGV.RowCount - 1 For j = 0 To myDGV.ColumnCount - 1 For k As Integer = 1 To myDGV.Columns.Count xlWorkSheet.Cells(1, k) = myDGV.Columns(k - 1).HeaderText xlWorkSheet.Cells(i + 2, j + 1) = myDGV(j, i).Value.ToString() Next Next Next 

When your DataGridView has AllowUserToAddRows as True (the default), the Cells in the blank/new row at the bottom will all contain Nothing . Most attempts to use the contents (for example, ToString ) will result in an NRE.

Remedio

Use a For/Each loop and test the IsNewRow property to determine if it is that last row. This works whether AllowUserToAddRows is true or not:

 For Each r As DataGridViewRow in myDGV.Rows If r.IsNewRow = False Then ' ok to use this row 

If you do use a For n loop, modify the row count or use Exit For when IsNewRow is true.


My.Settings (StringCollection)

Under certain circumstances, trying to use an item from My.Settings which is a StringCollection can result in a NullReference the first time you use it. The solution is the same, but not as obvious. Considerar:

 My.Settings.FooBars.Add("ziggy") ' foobars is a string collection 

Since VB is managing Settings for you, it is reasonable to expect it to initialize the collection. It will, but only if you have previously added an initial entry to the collection (in the Settings editor). Since the collection is (apparently) initialized when an item is added, it remains Nothing when there are no items in the Settings editor to add.

Remedio

Initialize the settings collection in the form's Load event handler, if/when needed:

 If My.Settings.FooBars Is Nothing Then My.Settings.FooBars = New System.Collections.Specialized.StringCollection End If 

Typically, the Settings collection will only need to be initialized the first time the application runs. An alternate remedy is to add an initial value to your collection in Project -> Settings | FooBars , save the project, then remove the fake value.


Puntos clave

You probably forgot the New operator.

o

Something you assumed would perform flawlessly to return an initialized object to your code, did not.

Don't ignore compiler warnings (ever) and use Option Strict On (always).


MSDN NullReference Exception

Another scenario is when you cast a null object into a value type . For example, the code below:

 object o = null; DateTime d = (DateTime)o; 

It will throw a NullReferenceException on the cast. It seems quite obvious in the above sample, but this can happen in more “late-binding” intricate scenarios where the null object has been returned from some code you don’t own, and the cast is for example generated by some automatic system.

One example of this is this simple ASP.NET binding fragment with the Calendar control:

 " /> 

Here, SelectedDate is in fact a property – of DateTime type – of the Calendar Web Control type, and the binding could perfectly return something null. The implicit ASP.NET Generator will create a piece of code that will be equivalent to the cast code above. And this will raise a NullReferenceException that is quite difficult to spot, because it lies in ASP.NET generated code which compiles fine…

It means that the variable in question is pointed at nothing. I could generate this like so:

 SqlConnection connection = null; connection.Open(); 

That will throw the error because while I’ve declared the variable ” connection “, it’s not pointed to anything. When I try to call the member ” Open “, there’s no reference for it to resolve, and it will throw the error.

To avoid this error:

  1. Always initialize your objects before you try to do anything with them.
  2. If you’re not sure whether the object is null, check it with object == null .

JetBrains’ Resharper tool will identify every place in your code that has the possibility of a null reference error, allowing you to put in a null check. This error is the number one source of bugs, IMHO.

It means your code used an object reference variable that was set to null (ie it did not reference an actual object instance).

To prevent the error, objects that could be null should be tested for null before being used.

 if (myvar != null) { // Go ahead and use myvar myvar.property = ... } else { // Whoops! myvar is null and cannot be used without first // assigning it to an instance reference // Attempting to use myvar here will result in NullReferenceException } 

Be aware that regardless of the scenario, the cause is always the same in .NET:

You are trying to use a reference variable whose value is Nothing / null . When the value is Nothing / null for the reference variable, that means it is not actually holding a reference to an instance of any object that exists on the heap.

You either never assigned something to the variable, never created an instance of the value assigned to the variable, or you set the variable equal to Nothing / null manually, or you called a function that set the variable to Nothing / null for you.

An example of this exception being thrown is: When you are trying to check something, that is null.

Por ejemplo:

 string testString = null; //Because it doesn't have a value (ie it's null; "Length" cannot do what it needs to do) if (testString.Length == 0) // Throws a nullreferenceexception { //Do something } 

The .NET runtime will throw a NullReferenceException when you attempt to perform an action on something which hasn’t been instantiated ie the code above.

In comparison to an ArgumentNullException which is typically thrown as a defensive measure if a method expects that what is being passed to it is not null.

More information is in C# NullReferenceException and Null Parameter .

If you have not initialized a reference type, and you want to set or read one of its properties, it will throw a NullReferenceException .

Ejemplo:

 Person p = null; p.Name = "Harry"; // NullReferenceException occurs here. 

You can simply avoid this by checking if the variable is not null:

 Person p = null; if (p!=null) { p.Name = "Harry"; // Not going to run to this point } 

To fully understand why a NullReferenceException is thrown, it is important to know the difference between value types and reference types .

So, if you’re dealing with value types , NullReferenceExceptions can not occur. Though you need to keep alert when dealing with reference types !

Only reference types, as the name is suggesting, can hold references or point literally to nothing (or ‘null’). Whereas value types always contain a value.

Reference types (these ones must be checked):

  • dinámica
  • objeto
  • cuerda

Value types (you can simply ignore these ones):

  • Numeric types
  • Integral types
  • Floating-point types
  • decimal
  • bool
  • User defined structs

Another case where NullReferenceExceptions can happen is the (incorrect) use of the as operator :

 class Book { public string Name { get; set; } } class Car { } Car mycar = new Car(); Book mybook = mycar as Book; // Incompatible conversion --> mybook = null Console.WriteLine(mybook.Name); // NullReferenceException 

Here, Book and Car are incompatible types; a Car cannot be converted/cast to a Book . When this cast fails, as returns null . Using mybook after this causes a NullReferenceException .

In general, you should use a cast or as , as follows:

If you are expecting the type conversion to always succeed (ie. you know what the object should be ahead of time), then you should use a cast:

 ComicBook cb = (ComicBook)specificBook; 

If you are unsure of the type, but you want to try to use it as a specific type, then use as :

 ComicBook cb = specificBook as ComicBook; if (cb != null) { // ... } 

You are using the object that contains the null value reference. So it’s giving a null exception. In the example the string value is null and when checking its length, the exception occurred.

Ejemplo:

 string value = null; if (value.Length == 0) // < -- Causes exception { Console.WriteLine(value); // <-- Never reached } 

The exception error is:

Unhandled Exception:

System.NullReferenceException: Object reference not set to an instance of an object. at Program.Main()

Simon Mourier gave this example :

 object o = null; DateTime d = (DateTime)o; // NullReferenceException 

where an unboxing conversion (cast) from object (or from one of the classes System.ValueType or System.Enum , or from an interface type) to a value type (other than Nullable<> ) in itself gives the NullReferenceException .

In the other direction, a boxing conversion from a Nullable<> which has HasValue equal to false to a reference type, can give a null reference which can then later lead to a NullReferenceException . The classic example is:

 DateTime? d = null; var s = d.ToString(); // OK, no exception (no boxing), returns "" var t = d.GetType(); // Bang! d is boxed, NullReferenceException 

Sometimes the boxing happens in another way. For example with this non-generic extension method:

 public static void MyExtension(this object x) { x.ToString(); } 

the following code will be problematic:

 DateTime? d = null; d.MyExtension(); // Leads to boxing, NullReferenceException occurs inside the body of the called method, not here. 

These cases arise because of the special rules the runtime uses when boxing Nullable<> instances.

While what causes a NullReferenceExceptions and approaches to avoid/fix such an exception have been addressed in other answers, what many programmers haven’t learned yet is how to independently debug such exceptions during development.

In Visual Studio this is usually easy thanks to the Visual Studio Debugger .


First, make sure that the correct error is going to be caught – see How do I allow breaking on ‘System.NullReferenceException’ in VS2010? Note 1

Then either Start with Debugging (F5) or Attach [the VS Debugger] to Running Process . On occasion it may be useful to use Debugger.Break , which will prompt to launch the debugger.

Now, when the NullReferenceException is thrown (or unhandled) the debugger will stop (remember the rule set above?) on the line on which the exception occurred. Sometimes the error will be easy to spot.

For instance, in the following line the only code that can cause the exception is if myString evaluates to null. This can be verified by looking at the Watch Window or running expressions in the Immediate Window .

 var x = myString.Trim(); 

In more advanced cases, such as the following, you’ll need to use one of the techniques above (Watch or Immediate Windows) to inspect the expressions to determine if str1 was null or if str2 was null.

 var x = str1.Trim() + str2.Trim(); 

Once where the exception is throw has been located, it’s usually trivial to reason backwards to find out where the null value was [incorrectly] introduced —

Take the time required to understand the cause of the exception. Inspect for null expressions. Inspect the previous expressions which could have resulted in such null expressions. Add breakpoints and step through the program as appropriate. Use the debugger.


1 If Break on Throws is too aggressive and the debugger stops on an NPE in the .NET or 3rd-party library, Break on User-Unhandled can be used to limit the exceptions caught. Additionally, VS2012 introduces Just My Code which I recommend enabling as well.

If you are debugging with Just My Code enabled, the behavior is slightly different. With Just My Code enabled, the debugger ignores first-chance common language runtime (CLR) exceptions that are thrown outside of My Code and do not pass through My Code

Adding a case when the class name for entity used in entity framework is same as class name for a web form code-behind file.

Suppose you have a web form Contact.aspx whose codebehind class is Contact and you have an entity name Contact.

Then following code will throw a NullReferenceException when you call context.SaveChanges()

 Contact contact = new Contact { Name = "Abhinav"}; var context = new DataContext(); context.Contacts.Add(contact); context.SaveChanges(); // NullReferenceException at this line 

For the sake of completeness DataContext class

 public class DataContext : DbContext { public DbSet Contacts {get; set;} } 

and Contact entity class. Sometimes entity classes are partial classes so that you can extend them in other files too.

 public partial class Contact { public string Name {get; set;} } 

The error occurs when both the entity and codebehind class are in same namespace. To fix this, rename the entity class or the codebehind class for Contact.aspx.

Reason I am still not sure about the reason. But whenever any of the entity class will extend System.Web.UI.Page this error occurs.

For discussion have a look at NullReferenceException in DbContext.saveChanges()

Another general case where one might receive this exception involves mocking classes during unit testing. Regardless of the mocking framework being used, you must ensure that all appropriate levels of the class hierarchy are properly mocked. In particular, all properties of HttpContext which are referenced by the code under test must be mocked.

See ” NullReferenceException thrown when testing custom AuthorizationAttribute ” for a somewhat verbose example.

I have a different perspective to answering this. This sort of answers “what else can I do to avoid it?

When working across different layers , for example in an MVC application, a controller needs services to call business operations. In such scenarios Dependency Injection Container can be used to initialize the services to avoid the NullReferenceException . So that means you don’t need to worry about checking for null and just call the services from the controller as though they will always to available (and initialized) as either a singleton or a prototype.

 public class MyController { private ServiceA serviceA; private ServiceB serviceB; public MyController(ServiceA serviceA, ServiceB serviceB) { this.serviceA = serviceA; this.serviceB = serviceB; } public void MyMethod() { // We don't need to check null because the dependency injection container // injects it, provided you took care of bootstrapping it. var someObject = serviceA.DoThis(); } } 

On the matter of “what should I do about it” , there can be many answers.

A more “formal” way of preventing such error conditions while developing is applying design by contract in your code. This means you need to set class invariants , and/or even function/method preconditions and postconditions on your system, while developing.

In short, class invariants ensure that there will be some constraints in your class that will not get violated in normal use (and therefore, the class will not get in an inconsistent state). Preconditions mean that data given as input to a function/method must follow some constraints set and never violate them, and postconditions mean that a function/method output must follow the set constraints again without ever violating them. Contract conditions should never be violated during execution of a bug-free program, therefore design by contract is checked in practice in debug mode, while being disabled in releases , to maximize the developed system performance.

This way, you can avoid NullReferenceException cases that are results of violation of the constraints set. For example, if you use an object property X in a class and later try to invoke one of its methods and X has a null value, then this will lead to NullReferenceException :

 public X { get; set; } public void InvokeX() { X.DoSomething(); // if X value is null, you will get a NullReferenceException } 

But if you set “property X must never have a null value” as method precondition, then you can prevent the scenario described before:

 //Using code contracts: [ContractInvariantMethod] protected void ObjectInvariant () { Contract.Invariant ( X != null ); //... } 

For this cause, Code Contracts project exists for .NET applications.

Alternatively, design by contract can be applied using assertions .

UPDATE: It is worth mentioning that the term was coined by Bertrand Meyer in connection with his design of the Eiffel programming language .

A NullReferenceException is thrown when we are trying to access Properties of a null object or when a string value becomes empty and we are trying to access string methods.

Por ejemplo:

  1. When a string method of an empty string accessed:

     string str = string.Empty; str.ToLower(); // throw null reference exception 
  2. When a property of a null object accessed:

     Public Class Person { public string Name { get; set; } } Person objPerson; objPerson.Name /// throw Null refernce Exception 

TL;DR: Try using Html.Partial instead of Renderpage


I was getting Object reference not set to an instance of an object when I tried to render a View within a View by sending it a Model, like this:

 @{ MyEntity M = new MyEntity(); } @RenderPage("_MyOtherView.cshtml", M); // error in _MyOtherView, the Model was Null 

Debugging showed the model was Null inside MyOtherView. Until I changed it to:

 @{ MyEntity M = new MyEntity(); } @Html.Partial("_MyOtherView.cshtml", M); 

Y funcionó.

Furthermore, the reason I didn’t have Html.Partial to begin with was because Visual Studio sometimes throws error-looking squiggly lines under Html.Partial if it’s inside a differently constructed foreach loop, even though it’s not really an error:

 @inherits System.Web.Mvc.WebViewPage @{ ViewBag.Title = "Entity Index"; List MyEntities = new List(); MyEntities.Add(new MyEntity()); MyEntities.Add(new MyEntity()); MyEntities.Add(new MyEntity()); } 
@{ foreach(var M in MyEntities) { // Squiggly lines below. Hovering says: cannot convert method group 'partial' to non-delegate type Object, did you intend to envoke the Method? @Html.Partial("MyOtherView.cshtml"); } }

But I was able to run the application with no problems with this “error”. I was able to get rid of the error by changing the structure of the foreach loop to look like this:

 @foreach(var M in MyEntities){ ... } 

Although I have a feeling it was because Visual Studio was misreading the ampersands and brackets.

What can you do about it?

There is a lot of good answers here explaining what a null reference is and how to debug it. But there is very little on how to prevent the issue or at least make it easier to catch.

Check arguments

For example, methods can check the different arguments to see if they are null and throw an ArgumentNullException , an exception obviously created for this exact purpose.

The constructor for the ArgumentNullException even takes the name of the parameter and a message as arguments so you can tell the developer exactly what the problem is.

 public void DoSomething(MyObject obj) { if(obj == null) { throw new ArgumentNullException("obj", "Need a reference to obj."); } } 

Use Tools

There are also several libraries that can help. “Resharper” for example can provide you with warnings while you are writing code, especially if you use their attribute: NotNullAttribute

There’s “Microsoft Code Contracts” where you use syntax like Contract.Requires(obj != null) which gives you runtime and compile checking: Introducing Code Contracts .

There’s also “PostSharp” which will allow you to just use attributes like this:

 public void DoSometing([NotNull] obj) 

By doing that and making PostSharp part of your build process obj will be checked for null at runtime. See: PostSharp null check

Plain Code Solution

Or you can always code your own approach using plain old code. For example here is a struct that you can use to catch null references. It’s modeled after the same concept as Nullable :

 [System.Diagnostics.DebuggerNonUserCode] public struct NotNull where T: class { private T _value; public T Value { get { if (_value == null) { throw new Exception("null value not allowed"); } return _value; } set { if (value == null) { throw new Exception("null value not allowed."); } _value = value; } } public static implicit operator T(NotNull notNullValue) { return notNullValue.Value; } public static implicit operator NotNull(T value) { return new NotNull { Value = value }; } } 

You would use very similar to the same way you would use Nullable , except with the goal of accomplishing exactly the opposite – to not allow null . Aquí hay unos ejemplos:

 NotNull person = null; // throws exception NotNull person = new Person(); // OK NotNull person = GetPerson(); // throws exception if GetPerson() returns null 

NotNull is implicitly cast to and from T so you can use it just about anywhere you need it. For example, you can pass a Person object to a method that takes a NotNull :

 Person person = new Person { Name = "John" }; WriteName(person); public static void WriteName(NotNull person) { Console.WriteLine(person.Value.Name); } 

As you can see above as with nullable you would access the underlying value through the Value property. Alternatively, you can use an explicit or implicit cast, you can see an example with the return value below:

 Person person = GetPerson(); public static NotNull GetPerson() { return new Person { Name = "John" }; } 

Or you can even use it when the method just returns T (in this case Person ) by doing a cast. For example, the following code would just like the code above:

 Person person = (NotNull)GetPerson(); public static Person GetPerson() { return new Person { Name = "John" }; } 

Combine with Extension

Combine NotNull with an extension method and you can cover even more situations. Here is an example of what the extension method can look like:

 [System.Diagnostics.DebuggerNonUserCode] public static class NotNullExtension { public static T NotNull(this T @this) where T: class { if (@this == null) { throw new Exception("null value not allowed"); } return @this; } } 

And here is an example of how it could be used:

 var person = GetPerson().NotNull(); 

GitHub

For your reference I made the code above available on GitHub, you can find it at:

https://github.com/luisperezphd/NotNull

Related Language Feature

C# 6.0 introduced the “null-conditional operator” that helps with this a little. With this feature, you can reference nested objects and if any one of them is null the whole expression returns null .

This reduces the number of null checks you have to do in some cases. The syntax is to put a question mark before each dot. Take the following code for example:

 var address = country?.State?.County?.City; 

Imagine that country is an object of type Country that has a property called State and so on. If country , State , County , or City is null then address will be null . Therefore you only have to check whether address is null`.

It’s a great feature, but it gives you less information. It doesn’t make it obvious which of the 4 is null.

Built-in like Nullable?

C# has a nice shorthand for Nullable , you can make something nullable by putting a question mark after the type like so int? .

It would be nice if C# had something like the NotNull struct above and had a similar shorthand, maybe the exclamation point (!) so that you could write something like: public void WriteName(Person! person) .

You can fix NullReferenceException in a clean way using Null-conditional Operators in c#6 and write less code to handle null checks.

It’s used to test for null before performing a member access (?.) or index (?[) operation.

Ejemplo

  var name = p?.Spouse?.FirstName; 

es equivalente a:

  if (p != null) { if (p.Spouse != null) { name = p.Spouse.FirstName; } } 

The result is that the name will be null when p is null or when p.Spouse is null.

Otherwise, the variable name will be assigned the value of the p.Spouse.FirstName.

For More details : Null-conditional Operators

The error line “Object reference not set to an instance of an object. ” states that you have not assigned instance object to a object reference and still you are accessing properies/methods of that object.

for example: let say you have a class called myClass and it contains one property prop1.

 public Class myClass { public int prop1 {get;set;} } 

Now you are accessing this prop1 in some other class just like below:

 public class Demo { public void testMethod() { myClass ref = null; ref.prop1 = 1; //This line throws error } } 

above line throws error because reference of class myClass is declared but not instantiated or an instance of object is not assigned to referecne of that class.

To fix this you have to instantiate (assign object to reference of that class).

 public class Demo { public void testMethod() { myClass ref = null; ref = new myClass(); ref.prop1 = 1; } } 

Interestingly, none of the answers on this page mention the two edge cases, hope no one minds if I add them:

Edge case #1: concurrent access to a Dictionary

Generic dictionaries in .NET are not thread-safe and they sometimes might throw a NullReference or even (more frequent) a KeyNotFoundException when you try to access a key from two concurrent threads. The exception is quite misleading in this case.

Edge case #2: unsafe code

If a NullReferenceException is thrown by unsafe code, you might look at your pointer variables, and check them for IntPtr.Zero or something. Which is the same thing (“null pointer exception”), but in unsafe code, variables are often cast to value-types/arrays, etc., and you bang your head against the wall, wondering how a value-type can throw this exception.

(Another reason for non-using unsafe code unless you need it, by the way)

NullReferenceException or Object reference not set to an instance of an object occurs when an object of the class you are trying to use is not instantiated. Por ejemplo:

Assume that you have a class named Student.

 public class Student { private string FirstName; private string LastName; public string GetFullName() { return FirstName + LastName; } } 

Now, consider another class where you are trying to retrieve the student’s full name.

 public class StudentInfo { public string GetStudentName() { Student s; string fullname = s.GetFullName(); return fullname; } } 

As seen in the above code, the statement Student s – only declares the variable of type Student, note that the Student class is not instantiated at this point. Hence, when the statement s.GetFullName() gets executed, it will throw the NullReferenceException.

Well, in simple terms:

You are trying to access an object that isn’t created or currently not in memory.

So how to tackle this:

  1. Debug and let the debugger break… It will directly take you to the variable that is broken… Now your task is to simply fix this.. Using the new keyword in the appropriate place.

  2. If it is caused on some database commands because the object isn’t present then all you need to do is do a null check and handle it:

     if (i == null) { // Handle this } 
  3. The hardest one .. if the GC collected the object already… This generally occurs if you are trying to find an object using strings… That is, finding it by name of the object then it may happen that the GC might already cleaned it up… This is hard to find and will become quite a problem… A better way to tackle this is do null checks wherever necessary during the development process. This will save you a lot of time.

By finding by name I mean some framework allow you to FIndObjects using strings and the code might look like this: FindObject(“ObjectName”);

If we consider common scenarios where this exception can be thrown, accessing properties withing object at the top.

Ex:

 string postalcode=Customer.Address.PostalCode; //if customer or address is null , this will through exeption 

in here , if address is null , then you will get NullReferenceException.

So, as a practice we should always use null check, before accessing properties in such objects (specially in generic)

 string postalcode=Customer?.Address?.PostalCode; //if customer or address is null , this will return null, without through a exception 

Literally the easiest way to fix a NullReferenceExeption has two ways. If you have a GameObject for example with a script attached and a variable named rb (rigidbody) this variable will start null when you start your game.
This is why you get a NullReferenceExeption because the computer does not have data stored in that variable.

I’ll be using a RigidBody variable as an example.
We can add data really easily actually in a few ways:

  1. Add a RigidBody to your object with AddComponent > Physics > Rigidbody
    Then go into your script and type rb = GetComponent();
    This line of code works best under your Start() or Awake() functions.
  2. You can add a component programmatically and assign the variable at the same time with one line of code: rb = AddComponent();

Further Notes: If you want unity to add a component to your object and you might have forgotten to add one, you can type [RequireComponent(typeof(RigidBody))] above your class declaration (the space below all of your usings).
Enjoy and have fun making games!

Reference types default to null to indicate that they are not referencing any object. Hence, if you try and access the object that is being referenced and there isn’t one, you will get a NullReferenceException .

For Ex:

 SqlConnection connection = null; connection.Open(); 

When you run this code, you will get :

 System.NullReferenceException: Object reference not set to an instance of an object. 

You can avoid this error by coding like this:

 if (connection != null){ connection.Open(); } 

Note: In order to avoid this error you should always initialize your objects before you try to do anything with them.

If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.

For me the reason was that I had rename the file and old file was still open.

It means you are trying to manipulate something which has reference but not yet initialized
The first thing to do here is check every instance created.

Use breakpoints , watches , inspect your varibale values.
Follow stack trace and search for exact row and column which is creating problem

To use methods and member of an object you first have to create that object. If you didn’t create it (variable that should hold the object is not initialized), but you try to use it’s methods or variables you’ll get that error.

Sometime you may just forgot to do initialization.

Edited: new can’t return null, but fire’s exception when failed. Long time ago it was the case in some languages, but not any more. Thanks @John Saunders for pointing that out.