10

The ArgumentNullException has a ParamName property to indicate which argument was passed as null.

Why does the NullReferenceException not have a similar property? Would it have been technically possible to implement within .Net?

David Neale
  • 16,498
  • 6
  • 59
  • 85
  • 1
    These two exceptions are different, the first one is thrown passing to its constructor the name of the null argument and it's normally thrown by your own code or the Framework, the second one is much more generic and I believe it's handled in a way down in IL where you do not have the real variable/object name anymore, since in IL everything has got compiled already and variables did not keep their initial names... this is my two cents guess... – Davide Piras Mar 10 '11 at 09:27

2 Answers2

9

A NullReferenceException is thrown by the CLR when it tries to navigate a null reference. This isn't necessarily associated with a variable, and in particular the CLR really doesn't care where it came from - it's just a value on the stack.

Compare that with ArgumentNullException which is explicitly thrown via code such as:

if (foo == null)
{
    throw new ArgumentNullException("foo");
}

There's no magic here - and you can even give the wrong name if you want. So they're really very different situations.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon - I guess the prevention of NREs is where code contracts can help a lot? – David Neale Mar 10 '11 at 09:38
  • 1
    when I use reflector or ILDASM, I recently noticed the variable name is there while before Reflector used to generate random names. Was there a change in .NET along the way? Do you want me to post a question for it? – Aliostad Mar 10 '11 at 09:40
  • @David: Yes, that's probably the most obvious contract :) – Jon Skeet Mar 10 '11 at 09:41
  • 1
    @Aliostad: That sounds like it's worth another question, yes. Not that I know the answer offhand :) – Jon Skeet Mar 10 '11 at 09:42
  • I did a bit of investigation and posted an answer. Thanks @Jon, your insight would be useful, it seems either reflector got better or pdb files have more info now. – Aliostad Mar 10 '11 at 11:25
1

OK, I know Jon has posted a nice answer but here is some more information.

Variable name is never compiled into the IL. (I was initially not sure but have checked) So as for the CLR, it is just a reference so it would not know what name it has and it would not even know its type since it is a null pointer and type information is retrieved from the type pointer of each object on the heap (getting type information for ValueTypes require boxing them).

However, Reflector does a very good job in reverse engineering your compiled assemblies and putting variable names back theer, but how when IL has no concept of variable name?? Well it turns out that it can do it using the metadata written to .pdb file. If you delete the file it will generate random names for your variables.

Aliostad
  • 80,612
  • 21
  • 160
  • 208