Is it correct that a instance method can be called on a null reference in IL..? Is there any example to show this..?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Yes, this is possible, as long as the method doesn't use
this
because the CLR does not do a null check forcall
instructions.You would have to modify the IL by hand as the C# compiler would almost always generate a
callvirt
instruction1.See this blog post for details and an example:
Sample
1In fact the reason that the C# compiler emits
callvirt
even in cases where a simplecall
instruction would be sufficient is to prevent calling instance methods on null references. With this behavior of the compiler users will get aNullReferenceException
so the weird situation of calling a method on a null pointer is avoided. Eric Gunnerson explained this in a blog post some time ago: Why does C# always use callvirt? Gishu also has a nice explanation in a related question.The CLR doesn't require it, it is an implementation detail of the language. C# and VB.NET perform the test. C++/CLI is a notable managed language that permits it. As long as the instance method doesn't reference any class members then nothing goes wrong. If is does, NullReferenceException will be raised as normal, merely giving you a hard time finding out why.
See my blog entry for info.
IL code sample: