Which exception is thrown when an instance method of a null object gets called access or modifies the field of a null object?

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

NullReferenceException Class

  • Reference

Definition

The exception that is thrown when there is an attempt to dereference a null object reference.

In this article

public ref class NullReferenceException : Exceptionpublic ref class NullReferenceException : SystemExceptionpublic class NullReferenceException : Exceptionpublic class NullReferenceException : SystemException[System.Serializable] public class NullReferenceException : SystemException[System.Serializable] [System.Runtime.InteropServices.ComVisible[true]] public class NullReferenceException : SystemExceptiontype NullReferenceException = class inherit Exceptiontype NullReferenceException = class inherit SystemException[] type NullReferenceException = class inherit SystemException[] [] type NullReferenceException = class inherit SystemExceptionPublic Class NullReferenceException Inherits ExceptionPublic Class NullReferenceException Inherits SystemExceptionInheritanceInheritanceAttributes

Remarks

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

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

    using System; using System.Collections.Generic; public class Example { public static void Main[string[] args] { int value = Int32.Parse[args[0]]; List names; if [value > 0] names = new List[]; names.Add["Major Major Major"]; } } // Compilation displays a warning like the following: // Example1.cs[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[] open System [] let main args = let value = Int32.Parse args[0] // Set names to null, don't initialize it. let mutable names = Unchecked.defaultof if value > 0 then names p.FirstName == nameToFind]; Console.WriteLine[found.FirstName]; } } public class Person { public static Person[] AddRange[String[] firstNames] { Person[] p = new Person[firstNames.Length]; for [int ctr = 0; ctr < firstNames.Length; ctr++] p[ctr] = new Person[firstNames[ctr]]; return p; } public Person[String firstName] { this.FirstName = firstName; } public String FirstName; } // The example displays the following output: // Unhandled Exception: System.NullReferenceException: // Object reference not set to an instance of an object. // at Example.Main[] 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 .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[]

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

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

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

    using System; public class Example { public static void Main[] { var pages = new Pages[]; if [! String.IsNullOrEmpty[pages.CurrentPage.Title]] { String title = pages.CurrentPage.Title; Console.WriteLine["Current title: '{0}'", title]; } } } public class Pages { Page[] page = new Page[10]; int ctr = 0; public Page CurrentPage { get { return page[ctr]; } set { // Move all the page objects down to accommodate the new one. if [ctr > page.GetUpperBound[0]] { for [int ndx = 1; ndx pages.GetUpperBound 0 then for ndx = 1 to pages.GetUpperBound 0 do pages[ndx - 1]

Chủ Đề