joerage
joerage

Reputation: 4923

Why 'Object reference not set to an instance of an object' is not more descriptive?

As a developer, we often encounter that exception: NullReferenceException with the well known error message:

Object reference not set to an instance of an object

Is it not possible for the .NET framework to return something a little bit more meaningful?

Something such as:

Object of type X named Y not set to an instance of an object

Upvotes: 5

Views: 754

Answers (3)

Nathan Taylor
Nathan Taylor

Reputation: 24606

To me this seems like purely an issue of preference. If it bugs you that much, you could always subclass the NullReferenceException and change the message. :)

What it comes down to though is the amount of information available when the message is created. Without manually passing in some extra information, simply determining the name of the field that was null inside the NullReferenceException would require reflection (possibly quite a bit), which is a rather heavy-load operation. Take for example the ArgumentNullException, in order to throw one in which the message indicates the offending parameter name, you have to pass in a string when you call it: throw new ArgumentNullException("param1").

The level of detail in an exception message is entirely up to the programmer who defines it, but it's prudent to avoid doing anything system intensive when throwing an exception.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

An object doesn't have a name - so how can it tell you the name? The null reference may have been loaded from a variable - or it might have been returned by a method, property etc.

The JIT could probably look at the stack information to work out what the declared reference type was, but I'm not sure how often this would help - and doubtless it would slow things down.

I can't say I've ever found this to be a huge burden when it comes to debugging - if there are lots of things which can be null on a single line, that usually suggests that it's worth splitting them up more.

Upvotes: 15

Tony The Lion
Tony The Lion

Reputation: 63190

Because its the most generic way of saying that.

Upvotes: 1

Related Questions