Bob Horn
Bob Horn

Reputation: 34325

Why can't the debugger/runtime tell me which object is null?

Code:

items.FirstOrDefault(x => x.Foo.Bar.BarId == snuh.BarId);

Error:

System.NullReferenceException: Object reference not set to an instance of an object.

The null object could be items, Foo, Bar, or snuh.

The debugger/runtime can tell me on which line of code the error is occurring. Why can't it also tell me which object is the problem?

Note: I know I can debug this and find out the answer. Is there a reason Visual Studio can't provide me with the name of the offending object?

Upvotes: 4

Views: 1830

Answers (3)

quantdev
quantdev

Reputation: 23813

Because the debugger or the compiler have the source symbols, so they can map a name to an address.

The runtime, however, doesn't know how a reference was named in your source code (it has been compiled).

Note that you if you (not the CLR) throwed the NullReferenceException, then you could have added any information in the embedded message.

Upvotes: 3

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239814

Due to optimizations, etc the relationship between "this reference stored in register R22/sitting in stack slot 5" and how that reference was actually obtained can be a difficult one to deduce.

All it knows, at this moment, is someone tried to dereference it and it turned out to be NULL.

And oftentimes, what it's trying to dereference may not have had a clear/understandable name in the source code either.

Upvotes: 2

Lex Webb
Lex Webb

Reputation: 2852

It's pretty common with most languages to receive a null pointer but not specify the object. I'm pretty sure its because it can't find the object in the first place in order to tell you what it is.

Upvotes: 0

Related Questions