Why "object reference not set to an instance of an object" doesn't tell us which object?

Posted by Saeed Neamati on Programmers See other posts from Programmers or by Saeed Neamati
Published on 2012-01-15T11:20:10Z Indexed on 2012/10/26 11:17 UTC
Read the original article Hit count: 500

Filed under:
|
|
|

We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why .NET doesn't give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

© Programmers or respective owner

Related posts about .NET

Related posts about exceptions