Trevor Daniel
Trevor Daniel

Reputation: 3954

How do I avoid 'Object reference not set to an instance of an object'?

I keep hitting the same problem over and over again, and I did it again just now. I wrote a line of code:

int LAID = db.GetLAByLatLong(address.Latitude, address.Longitude);

...and Visual Studio in reports no problem with the line whatsoever.

But when I run the code it reports:

Object reference not set to an instance of an object

What am i doing wrong? How come Visual Studio seems to say the code is fine, but at runtime it reports an error? I seem to be doing this a lot and I would really love to understand what I am doing wrong so I can avoid it.

Upvotes: 2

Views: 5940

Answers (3)

System Down
System Down

Reputation: 6260

The code compiles because for all intents and purposes it is correct.

However, that doesn't mean that it cannot cause errors in runtime. The error "Object reference not set to an instance of an object?" means that an object that you are using does not exist. In this line it could be the objects referenced by the variables db or address.

To know which, you'll have to debug the code. Put a breakpoint on that line (click on the space to the left of the line) and press F5. The code will run and then stop at that line, where you can inspect what all the variables contain.

Upvotes: 3

Daniel A.A. Pelsmaeker
Daniel A.A. Pelsmaeker

Reputation: 50326

You have to check which variables might be null. See this answer for a list of steps that help you work it out.

In this case one of the db and address variables might be null, and that is the most common cause for a NullReferenceException.

Upvotes: 2

Eric J.
Eric J.

Reputation: 150108

You have two objects in your code:

db

and

address

You are referencing both objects in the code shown. At least one of them is null.

To avoid that problem, ensure that you have initialized both objects before the code runs. You can also add checks such as

if (db == null) throw new Exception("The variable db is null.");

Upvotes: 8

Related Questions