Object reference not set to an instance of an object

“Object reference not set to an instance of an object” is probably the most common run-time exception message spat-out by the .Net framework, and most programmers will probably encounter this more often than any other framework exception type.

This exception, or more specifically a “System.NullReferenceException” is always caused when code tries to access an instance of any object, when the object has not yet been created and/or returned via a constructor, or some method.

Back to basics.

Object oriented programming is a form of programming wherein things called “Objects” are given “responsibility” for data, and for various operations. Each Object has a kind of blueprint, called a “Class”, as shown in the following code:

public class Chair
{
    public Chair() { }
    public void Sit() { }
}

In order to use this object, you must create an “instance” of it, so to do that with the above class:

Chair myChair;
myChair = new Chair();
myChair.Sit();
  1. Memory Allocation

    Chair myChair;
    

    This line of code designates some memory to be used by your program for holding a “Chair” object. Think of this line, like setting aside some wood and nails to build a real chair.

  2. Constructing your object

    myChair = new Chair();
    

    This line of code creates an “Instance” of a “Chair” class, and assigns it to the variable “myChair” so that we may use it. To continue the above analogy, this is akin to looking at the blueprints for a chair, and using the assigned resources of wood & nails (Memory, in the case of our program) and actually creating the Chair.

  3. Using the Object

    myChair.Sit();
    

    Now that we have an actual chair object, we can sit on it. If, however, you forget to include the line:

    myChair = new Chair();
    

    Or, somehow your “myChair” object gets set to null before the myChair.Sit(); method-call, then a System.NullReferenceException will be thrown.

If your object is unassigned (or null) you’re essentially tying to “Sit()” on nothing, and your program will fall on its arse.

comments powered by Disqus