Object reference not set to an instance of an object

The infomous Object reference not set to an instance of an object error occurs when you try to reference or use an object that has not been set to a valid "value" or instance.  For example, let's assume you have a Class "Person" that has a property Name.  If you try to access the Name property and your Person object is not set to an instance, you will receive the Object reference not set to an instance of an object error.

In code:

Person p = null;
p.Name = "John Doe";

This is an obvious case, but what makes this error difficult to track down at times is when you do not know why you do not have an instance of the object.  This can occur for a variety of reasons.  If you are able to create a unit test (or already have one) this can help you to track down the root cause.  You can also rely on the stack trace and/or debug the offending code.

Add comment