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

☆樱花仙子☆ 提交于 2019-12-30 08:13:49

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5257626/is-there-a-reason-why-nullreferenceexception-does-not-give-the-name-of-the-varia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!