How often do you see this error? If you're like me, you see it a lot. I've seen Microsoft techies get balled up in variations of this error in presentations. Recently, I was coding an example for an article here when I ran into it again. It took me longer than I want to tell you to discover what was wrong.
In this particular case, the code that was creating the error looked like this:
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.
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 my bug above, no such help was available.
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) told me that the actual problem was that I 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?