105

Regarding this .NET unhandled exception message:

Object reference not set to an instance of an object.

Why doesn't .NET show which object is null?

I know that I can check for null and resolve the error. However, why doesn't .NET help pointing out which object has a null-reference and which expression triggered the NullReferenceException?

18
  • 2
    When this happens, rewrite the line it happened on so it checks each possible result for null first - then you'll know exactly what it was. Either that, or have Visual Studio's amazing debugger attached, which breaks the instant an exception occurs and lets you see what is null :) Commented Feb 9, 2013 at 11:24
  • 5
    Not really, he simply asks why the .NET framework does not help the programmer to show which object is null. I guess it's the performance penalty (you'd need reflection). but I am not sure either. Commented Feb 9, 2013 at 11:27
  • 1
    @bas: While that is true, the question is a bit misleading in that it should be asking about a "part of an expression", not an "object". That also explains why mere reflection won't help, but some extensive debug information will be required. Commented Feb 9, 2013 at 11:29
  • 4
    Still I am curious for the answer. It's kind off similar to .net exceptions not helping to point out which key does not exist in a dictionary. Also, I don't understand the devotes on the question. Commented Feb 9, 2013 at 11:30
  • 13
    Terminology please: An object is never null. An object reference might be though. But an object reference is just a location in memory - how would it help you, unless you have a debugger attached anyway? Commented Feb 9, 2013 at 11:47

5 Answers 5

172

(For information about the new exception helper in Visual Studio 2017 see the end of this answer)


Consider this code:

String s = null;
Console.WriteLine(s.Length);

This will throw a NullReferenceException in the second line and you want to know why .NET doesn't tell you that it was s that was null when the exception was thrown.

To understand why you don't get that piece of information you should remember that it is not C# source that executes but rather IL:

IL_0001:  ldnull      
IL_0002:  stloc.0     // s
IL_0003:  ldloc.0     // s
IL_0004:  callvirt    System.String.get_Length
IL_0009:  call        System.Console.WriteLine

It is the callvirt opcode that throws the NullReferenceException and it does that when the first argument on the evaluation stack is a null reference (the one that was loaded using ldloc.0).

If .NET should be able to tell that it was s that was a null reference it should in some way track that the first argument on the evaluation stack originated form s. In this case it is easy for us to see that it is s that was null but what if the value was a return value from another function call and not stored in any variable? Anyway, this kind of information is not what you want to keep track of in a virtual machine like the .NET virtual machine.


To avoid this problem I suggest that you perform argument null checking in all public method calls (unless of course you allow the null reference):

public void Foo(String s) {
  if (s == null)
    throw new ArgumentNullException("s");
  Console.WriteLine(s.Length);
}

If null is passed to the method you get an exception that precisely describes what the problem is (that s is null).


Four years later Visual Studio 2017 now has a new exception helper that will try to tell what is null when a NullReferenceException is thrown. It is even able to give you the required information when it is the return value of a method that is null:

Visual Studio 2017 exception helper

Note that this only works in a DEBUG build.

Sign up to request clarification or add additional context in comments.

20 Comments

Line numbers and source file names aren't stored in the IL code itself, either, or are they? Yet, they can be made available for debugging.
@MartinLiversage: Exactly. So the question boils down to: Why isn't there sufficient info stored in the symbols files that also tells what expression in the code was evaluated to null.
@MartinLiversage: Symbol files are accessible in a way so that upon an exception, along with the exception message, the source file and line number can be displayed in the output of the debugger. So, the question is, what's the reason for not including some more info on what exactly returned null - note that the OP doesn't claim he or she wants to know that for release builds, as well, debug builds may be sufficient.
Hmm, and we should't forget that it's not even the IL that actually executes, but rather native code built from it at runtime.
@MartinLiversage: No-one in this question claims we want this perfectly supported for release builds. Anyway, I don't quite see the problem in correlating the IL opcode that uses an object reference (that may turn out to be null) with the source file line and column that returned that object reference.
|
9

How do you want the error message in the following case look like?

AnyObject.GetANullObject().ToString();

private object GetANullObject()
{
  return null;
}

No variable names to report here!

4 Comments

I suspect the OP is looking for the expression in the source code that returns null, not the object. I've added a respective comment to the question and hope he or she will clear things up. If my suspicion is correct, the OP would expect something like Object reference obtained from AnyObject.GetANullObject() not set to an instance of an object. as the error message.
@O.R.Mapper I agree. I would have just put my "answer" in a comment to the OP, if I had enough reputation points to add a comment!
"a null reference attempted to call the ToString() method of the Class XYZ" would be more helpful than what we get now.
The most helpful thing would be a stack trace showing, at each call level, exactly what line, in what file, resulted in the error. Oh, wait ... that's what it does now!
1

Well, that's upto engineers at Microsoft to answer. But you can obviously use a debugger and add watch to find out which of those has a problem.

However, the exception is NullReferenceException which means the reference does not exist . You can't get the object which hasn't been created at all.

but why .NET don't tell us which object is null? Because it does not know which object is null. The object simply does not exist!

Same is the case when I say, C# is compiled to .NET IL code. The .NET IL code does not know the names or expressions. It only knows references and their location. Here too, you cannot get what does not exist. The expression or the variable name does not exist.

Philosophy: You cannot make an omlette if you don't have an egg in the first place.

9 Comments

that's not an answer either :)
How do you get the reference if it doesn't exist? @Bas
"Well, that's upto engineers at Microsoft to answer.". So let them shed a light on this instead of stating the obvious
@bas we can decide what is logical at the very least. Logically the object does not exist. How will you catch it with an exception and then print out the name of the object? It just does not exist. Not even on stack..
so the answer is that's is virtually impossible to point out which object has a nullreference? That's an answer too. I am not stating that I know, I just like the question :). +1 for all the effort :p
|
1

Not sure, but this may be because .Net doesn't knows whether it is predefined class or user-defined. If it is predefined then it can be null(like string which occupies 2 Bytes) but if it is user-defined than we have to create an instance of it so that it knows that this object will occupy this much memory. So therefore it throws error at run-time.

Comments

-2

Good question. The message box is just short of useless. Even if it's buried a mile deep from the references definition, some class or assembly or file or other information would be better than what they currently provide (read: better than nothing).

Your best option is to run it in the debugger with debugging information, and your IDE will break at the offending line (rather clearly demonstrating that useful information is in fact available).

Comments