
The obscure, and generally least informative error "Object reference not set to an instance of an object", is arguably the most annoying error an ASP.NET developer will encounter.
When initially starting .NET dev, I would encounter it daily, and it would be a major cause of headaches for me.
Here is some sample code:

The Cause:
The error is caused when one tries to access a property of an un-initialized object (the object is null).
In the code there is a class called DummyMotherClass, and it has just one property called "ChildDummy" of type DummyClass.
Above, when a variable of type DummyMotherClass is declared, the ChildDummy property is not instantiated.
So, after the line "DummyMotherClass TestInstance = new DummyMotherClass();", the TestInstance.ChildDummy is null.
If you try to access any property of the ChildDummy property, the "Object reference not set to an instance of an object" will be thrown. This happens because you're essentially trying to do something like
The Solution:To fix the error, you can:
- Check if TestInstance.ChildDummy != null, before attempting to use one of the ChildDummy's properties.
- Initiallize the TestInstance.ChildDummy manually.
- Surround the line in question with a try { } catch {} statement (may degrade performance though).

This also could have been done just below the "DummyMotherClass TestInstance = new DummyMotherClass();" line, if you do not have access to the constructor. Ie "TestInstance.ChildDummy = new DummyClass();"
Debugging:
I have not found a better way to check which object is null other than starting the Visual Studio debugger. The error page tells you which line is causing the problem, but it doesn't tell you which object is null. The error becomes less useful when you have the properties chained across multiple levels. Esp when using LINQ to SQL (ie: following foreign key relationships).
I usually just hover over each object in the line starting with the leftmost one, and continue sweeping right until the object in question is null.
After finding the causing object I add some if statements to check for nulls, or look for a more general solution to address the problem if it may reoccur in other places in code.Conclusion:
Hope this helps to avoid some frustrating moments!

0 comments:
Post a Comment
Anyone can write comments. However they will not show up immediately, as they will be checked for spam, relevance, etc...