Object Reference Not Set to an Instance of an Object

Common Error in .NET

How often do you see this error? Quite frequently. We've seen Microsoft techies get balled up in variations of this error in presentations.

In this particular case, the code that was creating the error looked like this:

XDoc.Element("myXElements").Add( _
   New XElement("myXElements", ContentVar))

In a case like this, the first question that came to mind is, "Which object? There are a bunch of them."

We'll get back to this after looking at exactly what this error is trying to tell you.

Understanding Types in .NET

In .NET, types are either "value types" or "reference types".

Value types are stored on the directly on the "stack" - a section of memory. Since they're addressed directly, they're initialized when they are created and you don't need a "New" operator for them.

Reference types are objects stored on the "managed heap". They get their name because the variable actually consists of a pointer in memory - a reference - to the location of the object on the heap.

Since reference types are actually pointers to memory, their value can be "Nothing". That is, there is no memory address. This can happen in a variety of ways and that's why this error can be so frustrating. The possibilities include:

  • You never assigned anything to the variable.
  • You never created an instance of the value assigned to the variable.
  • You set the variable equal to Nothing, or a called function did the same thing.

    One of the simplest demonstrations uses a string variable (which is a reference type in VB.NET). In the code below, a location for a pointer is created on the heap, but it doesn't point to anything so the value is "Nothing".

    Dim a As String
    If a.Length = 0 Then
     Console.Write("Yes")
    End If

    The compiler flags a as a problem in this case for you.

    In the bug above, no such help was available.

    Solving the Problem

    In this particular case, the details associated with the NullReferenceException were useless. The fastest way to find the source of the bug was to check each object in the statement with QuickWatch. That (eventually) revealed that the actual problem was attempting to add an element to an XML document out of sequence:

    <XDoc>
     <anotherElement>
     <myXElements />
     </anotherElement>
    </XDoc>

    Who knew this would create a null reference exception?

    Format
    mla apa chicago
    Your Citation
    Mabbutt, Dan. "Object Reference Not Set to an Instance of an Object." ThoughtCo, Nov. 28, 2017, thoughtco.com/common-object-reference-mistake-3974464. Mabbutt, Dan. (2017, November 28). Object Reference Not Set to an Instance of an Object. Retrieved from https://www.thoughtco.com/common-object-reference-mistake-3974464 Mabbutt, Dan. "Object Reference Not Set to an Instance of an Object." ThoughtCo. https://www.thoughtco.com/common-object-reference-mistake-3974464 (accessed December 12, 2017).