System.NullReferenceException

Namespace: System
Indicates that an attempt to dereference a null object reference has occurred.

Syntax

public sealed class NullReferenceException : SystemException

Inheritance

System.Object
System.Exception
System.SystemException
System.NullReferenceException

Remarks

A NullReferenceException is thrown when you try to use an object variable that is currently null. This often happens when you call a method or access a member of an object without initializing the object variable first.

For example, the following code will throw a NullReferenceException because the myString variable is null:

string myString = null;
int length = myString.Length; // This line throws NullReferenceException

To avoid this exception, you should always check if an object variable is null before attempting to use it, or ensure that it is properly initialized.

Constructors

Name Description
NullReferenceException() Initializes a new instance of the NullReferenceException class.
NullReferenceException(string message) Initializes a new instance of the NullReferenceException class with a specified error message.
NullReferenceException(string message, Exception innerException) 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 the current exception.

Fields

No public fields are exposed by this class.

Properties

Name Description
HResult Gets or sets the HRESULT value assigned to the specified exception.
InnerException Gets a reference to the inner exception that is the cause of the current exception.
Message Gets an error message that describes the current exception.
Source Gets or sets the name of the application or the object that causes the error.
StackTrace Gets a string representation of the immediate frames of the call stack.
TargetSite Gets the method that throws the current exception.

Methods

Name Description
ToString() Overrides System.Exception.ToString() to include the name of the exception and the decimal representation of the HRESULT.