A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception below:

NullReferenceException Class (System) | Microsoft Learn

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 forgot to instantiate a reference type. In the following example, names is declared but never instantiated (the affected line is commented out in the C# example since it doesn't compile):

    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()
    

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

    using System.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
    
  • You forgot to dimension an array before initializing it. In the following example, values is declared to be an integer array, but the number of elements that it contains is never specified. The attempt to initialize its values therefore throws a NullReferenceException exception.

    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()
    

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

    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
    

    For more information on declaring and initializing arrays, see Arrays and Arrays.

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

    The code in the following example assumes that the Array.Find method always returns Person object whose FirstName field matches a search string. Because there is no match, the runtime throws a NullReferenceException exception.

    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()
    

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

    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
    
  • You're using an expression (for example, you chained 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.

    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()
    

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

    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.
    
  • You're enumerating the elements of an array that contains reference types, and your attempt to process one of the elements throws a NullReferenceException exception.

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

    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()
    

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

    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
    
  • A method when it accesses a member of one of its arguments, but that argument is null. The PopulateNames method in the following example throws the exception at the line 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()
    

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

  • A list is created without knowing the type, and the list was not initialized. The GetList method in the following example throws the exception at the line 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
    

    To address this issue, make sure that the list is initialized (one way to do this is to call Activator.CreateInstance instead of FormatterServices.GetUninitializedObject), or handle the thrown exception in a try…catch…finally block. For more information, see Exceptions.

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

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

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


    RetroSearch is an open source project built by @garambo | Open a GitHub Issue

    Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

    HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4