开发者

Is there a reason why NullReferenceException does not give the name of the variable?

The ArgumentNullException has a ParamName property t开发者_如何学运维o 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜