System.NullReferenceException Class
Represents the error that occurs when there is an attempt to dereference a null object reference.

See Also: NullReferenceException Members

Syntax

[System.Runtime.InteropServices.ComVisible(true)]
public class NullReferenceException : SystemException

Remarks

Note:

Applications throw the ArgumentNullException rather than NullReferenceException .

The following CIL instructions throw NullReferenceException :

  • callvirt
  • cpblk
  • cpobj
  • ldelema
  • ldelem.<type>
  • ldfld
  • ldflda
  • ldind.<type>
  • ldlen
  • stelem.<type>
  • stind.<type>
  • stfld
  • throw
  • unbox
  • initblk

Thread Safety

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

Example

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

Example

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

Requirements

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