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 doesn't .NET 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?
Update:
The exception The system cannot find the file specified
has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist.
instead of that general message? As a developer, I vote yes.
Best Answer
The
NullReferenceException
basically tells you: you are doing it wrong. Nothing more, nothing less. It's not a full-fledged debugging tool, on the contrary. In this case I'd say you're doing it wrong both becauseI'm a big fan of checking everything before things start going wrong, and providing good information to the developer. In short: write checks using
ArgumentNullException
and the likes and write the name yourself. Here's a sample:You could also look into Code Contracts, it has it quirks but it works pretty well and saves you some typing.