Why do I get the error “Object reference not set to an instance of an object”?

Avatar

The code is trying to access a member of a reference type variable that is set to null.

Given the following class, let’s examine some code that could be in the Main method:

Looking at Main, notice that foo is set to null.  Your situation will not be this explicit because the variable you are trying to use could be a class field, parameter, or local variable that was once instantiated but was subseqently set to null.  Given that foo is null, the following code will throw a NullReferenceException:

Since foo is null, you can not use its members.  This was a property, but the following code demonstrates calling a method:

The code above throws a NullReferenceException because foo is still null.  It doesn’t matter that the first call was a property and the second is a method – they are both members of the type.

Now, to fix this problem, you must ensure that foo is instantiated before it is used.  The following code instantiates foo and the previous problems are solved:

Since foo now refers to a valid instance, the code can call any of its members.  This was easier than many null reference problems.  Sometimes you have multiple levels of indirection, leaving you with a scenario you didn’t expect.  Assuming that foo now references an object, there is still a problem with the following code:

The problem occurs in the code above because BarMethod returned null, which means that the code is trying to call the Trim method on a string reference that is set to null

The proper way to fix this problem is to debug BarMethod to find out why it returned null.  That assumes BarMethod is not supposed to return null.  If, in your application, it made sense for BarMethod to sometimes return null, then you would have to check the return value of BarMethod before you called any members of the return value.

[Author: Joe Mayo]

Avatar

Follow    

Tagged

No Comments.