System.NullReferenceException Class

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

See Also: NullReferenceException Members


public class NullReferenceException : SystemException


A NullReferenceException exception is thrown when you try to access a member on a type whose value is null. The following example illustrates one such scenario:

code reference: System.NullReferenceException.Class#1

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.

code reference: System.NullReferenceException.Class#2

More commonly, a NullReferenceException exception is thrown by a method that is passed null. Some methods validate the arguments that are passed to them. If they do and one of the arguments is null, the method throws an ArgumentNullException exception. Otherwise, it throws a NullReferenceException exception. The following example illustrates this scenario.

code reference: System.NullReferenceException.Class#3

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 Handling and Throwing 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.#ctor constructors.

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.


The following example demonstrates an error that causes a NullReferenceException exception.

C# Example

using System;
public class Ints {
   public int[] myInts;
public class NullRefExample {
   public static void Main() {
      Ints ints = new Ints();
      try {
         int i = ints.myInts[0];
      catch( NullReferenceException e ) {
         Console.WriteLine( "Caught error: {0}.", e);

The output is


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


Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0,,