Syntax

Remarks

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.