Why Doesn’t ‘Object Reference Not Set to an Instance of an Object’ Specify Which Object?

exceptionsloggingnetnull

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 because

  • there is a NullReferenceException
  • you didn't prevent it in a way you know why/where it happened
  • and also maybe: a method requiring 20 objects seems a bit off

I'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:

void Method(string a, SomeObject b)
{
    if (a == null) throw ArgumentNullException("a");
    if (b == null) throw ArgumentNullException("b");

    // See how nice this is, and what peace of mind this provides? As long as
    // nothing modifies a or b you can use them here and be 100% sure they're not
    // null. Should they be when entering the method, at least you know which one
    // is null.
    var c = FetchSomeObject();
    if(c == null)
    {
        throw InvalidOperationException("Fetching B failed!!");
    }

    // etc.
}

You could also look into Code Contracts, it has it quirks but it works pretty well and saves you some typing.

Related Topic