Object reference not set to an instance of an object

.NET Best Practices

Various places that the dreaded object reference not set error can hide


Date : 2009-01-13
This is definitely one of my most common errors which irritates me because I know it means I've done something stupid. There are a few of these errors that hide rather well. I'm going to share my favorite one in hopes that it saves you some time. Feel free to add a comment with one that has you stuck and we'll see if we can help, maybe it will get on the alltime favorite list.

I wont insult your intelligence by simply reminding you to initialize variables, although that is the basic cause behind this error. Some object is not initialized correctly or completely.

I doubt that many of us are setting private variables within one scope and then expecting to use them in another. If something like that is the problem you need to go fix it quickly without letting anyone see because that is a horribly bush league thing to do.

My all time favorite is below, on a good day I'll manage to sneak this error in at least twice.

Bad C#
Code:
  myObject = new myObjectType[2];
  myObject[0].property = 10;


Looks good to me, lets run that thing... “Object reference not set to an instance of an object”

Because, of course, while we did initialize the array, we still need to construct the object within the array before we can use it.

Good C#
Code:
  myObject = new myObjectType[2];
  myObject[0] = new myObjectType();
  myObject[0].property = 10;


Then we're good to go.
I hope that saves you some time, now tell us about the error that's bothering you.

Comments :

No comments yet
  • Search For Articles