Is it correct that a instance method can be called on a null reference in IL..?
Is there any example to show this..?
Is it correct that a instance method can be called on a null reference
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, this is possible, as long as the method doesn’t use
thisbecause the CLR does not do a null check forcallinstructions.You would have to modify the IL by hand as the C# compiler would almost always generate a
callvirtinstruction1.See this blog post for details and an example:
Sample
1In fact the reason that the C# compiler emits
callvirteven in cases where a simplecallinstruction would be sufficient is to prevent calling instance methods on null references. With this behavior of the compiler users will get aNullReferenceExceptionso 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.