Edit

Share via


NullReferenceException Class

Definition

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

C#
public class NullReferenceException : Exception
C#
public class NullReferenceException : SystemException
C#
[System.Serializable]
public class NullReferenceException : SystemException
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class NullReferenceException : SystemException
Inheritance
NullReferenceException
Inheritance
NullReferenceException
Attributes

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:

Note

You can avoid most NullReferenceException exceptions in C# by using the null-conditional operator (?.) or the null-coalescing operator (??). For more information, see Nullable reference types. The following C# examples assume the nullable context is disabled (not recommended).

  • 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):

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

    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.

    C#
    using System.Collections.Generic;
    
    public class AnotherExample
    {
        public static void Main()
        {
            List<string> names = ["Major Major Major"];
        }
    }
    
  • 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.

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

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

    C#
    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
    

    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.

    C#
    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.
    

    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.

    C#
    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
    
  • 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.

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

    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:

    C#
    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.
    
  • 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.

    C#
    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.
    

    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.

    C#
    string[] values = [ "one", null, "two" ];
    for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
        Console.Write("{0}{1}",
                      values[ctr] != null ? values[ctr].Trim() : "",
                      ctr == values.GetUpperBound(0) ? "" : ", ");
    Console.WriteLine();
    
    // The example displays the following output:
    //       one, , two
    
  • A 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);.

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

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

    C#
    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.

For a list of initial property values for an instance of NullReferenceException, see the NullReferenceException constructors.

When to handle NullReferenceException exceptions

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

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

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

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

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

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

Constructors

NullReferenceException()

Initializes a new instance of the NullReferenceException class, setting the Message property of the new instance to a system-supplied message that describes the error, such as "The value 'null' was found where an instance of an object was required." This message takes into account the current system culture.

NullReferenceException(SerializationInfo, StreamingContext)
Obsolete.

Initializes a new instance of the NullReferenceException class with serialized data.

NullReferenceException(String, Exception)

Initializes a new instance of the NullReferenceException class with a specified error message and a reference to the inner exception that is the cause of this exception.

NullReferenceException(String)

Initializes a new instance of the NullReferenceException class with a specified error message.

Properties

Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink

Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException

Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message

Gets a message that describes the current exception.

(Inherited from Exception)
Source

Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace

Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite

Gets the method that throws the current exception.

(Inherited from Exception)

Methods

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)
Obsolete.

When overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType()

Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Creates and returns a string representation of the current exception.

(Inherited from Exception)

Events

SerializeObjectState
Obsolete.

Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also