Static method vs instance method, Reflection.Emit and DynamicMethod

On IL level, when you’re accessing method’s parameters there’s a <sarcasm>small</sarcasm> difference between static and instance methods. Instance methods have implicitly 0th parameter set to this. So if you want to access your 1st parameter in instance method you have to emit ldarg.1, and in static method you have to emit ldarg.0.

It’s basic OO, yet it took me 2h to find out that this was the cause why my DynamicMethod was throwing NullReferenceException. I created a method that looked kind of like what I wanted my dynamic method to look like, and looked at its IL in Reflector. It was exactly what I was emitting to my dynamic method, yet it kept failing.

After way to much time it came to my mind that my DynamicMethod was static, whereas my reference method was instance.


Technorati Tags: , ,