C# NullReferenceException and Null Parameter

by Sam Allen - Updated January 8, 2010

You are encountering the NullReferenceException in your C# program written for the .NET Framework. This exception is very common and indicates that you are trying to access member fields or function types on an object reference that points to null. Here we look at a situation that can cause the NullReferenceException, and then look at how you can modify a method to prevent the exception on null parameters, using the C# programming language.

NullReferenceException

First, it is useful to look at an example of a short program that causes this exception to be raised. The program explicitly assigns the string reference variable to the null literal. This means that the string variable does not point to any object on the managed heap. It is equivalent to a null pointer.

~~~ Program that raises NullReferenceException (C#) ~~~

using System;

class Program
{
    static void Main()
    {
        string value = null;
        if (value.Length == 0) // <-- Causes exception
        {
            Console.WriteLine(value); // <-- Never reached
        }
    }
}

~~~ Output of the program ~~~

Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Program.Main() in C:\Users\...

Accessing property. The program text above defines the Main entry point. The string reference variable is assigned to the null literal. Next, the Length property is accessed on the string reference. The program compiles correctly, but will always throw an execution. You cannot access a property like Length on a null reference.

Preventing NullReferenceException

Here we look at one way you can prevent the null reference exception from being thrown. Often in programs, methods receive reference value parameters. The parameters contain the storage location of an object on the managed heap. However, if the parameter points to null, the method will not know this at compile-time. Instead, you must check the parameter for null at the method start.

--- Program that checks for null in method (C#) ---

using System;

class Program
{
    static void Main()
    {
        // Create an array and use it in method.
        int[] array = new int[2];
        array[0] = 1;
        array[1] = 2;
        Test(array);

        // Use null reference in method.
        array = null;
        Test(array); // <-- Won't crash
    }

    static void Test(int[] array)
    {
        if (array == null)
        {
            // You can throw an exception here, or deal with the argument.
            return;
        }
        int rank = array.Rank;
        Console.WriteLine(rank);
    }
}

Notes on the program text. The Main entry point is where control flow begins in the example. An array containing two elements is passed to the Test method. The Test method internally checks the reference value parameter against the null literal. It will therefore not throw when passed a null reference, as you can see in the latter part of the Main method.

Ignoring exceptions

Exception handling is a complex topic and developers have different strategies regarding it. However, the common theme to the best approaches is to always log the exceptions and work to prevent them from happening in normal runtime operation. In many programs, you can use ArgumentNullException to notify the caller of errors.

Handling null references. If you have total control over the callers of a method and it can never be called with a null parameter, it is preferable to not check the parameter for null. For libraries and code APIs that will be used by others, more careful parameter checking to avoid NullReferenceExceptions is best.

Opcodes

Microsoft helpfully lists the opcodes in the MSIL that will cause the NullReferenceException to be thrown in some conditions. Usually it is easiest to step through your code in Visual Studio, but analyzing opcodes also provides insight into the functionality of your code.

(Visit msdn.microsoft.com.)

Summary

Here we looked the NullReferenceException error reporting class in the System namespace, using the C# language. You will encounter this exception when you attempt to access a member on a null variable. This will only occur on instances that are reference types. You will need to deal with null parameters in certain cases. Finally, you can catch NullReferenceException with a specific catch clause.

(Do not copy this page.)

Dot Net Perls | Search
Exceptions | Collection Was Modified Exception | Exception Overview | File.Delete Exceptions | FileNotFoundException Tips | KeyNotFoundException Fix
C# | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method | File.Replace Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen