Call a dynamically generated method on a ILGenerator on the same type

Posted by Thiado de Arruda on Stack Overflow See other posts from Stack Overflow or by Thiado de Arruda
Published on 2010-05-08T16:42:16Z Indexed on 2010/05/08 16:48 UTC
Read the original article Hit count: 244

Normally, when I want to call a dynamic method in another ILGenerator object that is writing a method on the same type I do the following :

generator.Emit(OpCodes.Ldarg_0); // reference to the current object
generator.Emit(OpCodes.Ldstr, "someArgument");
generator.Emit(OpCodes.Call, methodBuilder); //this methodbuilder is also defined on this dynamic type.

However, I faced the following problem: I cant have a reference to the methodbuilder of the method I want to call, because it is generated by another framework(I only get a reference to the current TypeBuilder). This method is defined as protected virtual(and overriden on the methodbuilder I cant get a reference to) in the base class of the current dynamic type and I can get a reference to it by doing this :

generator.Emit(OpCodes.Ldarg_0); // reference to the current object
generator.Emit(OpCodes.Ldstr, "someArgument");
generator.Emit(OpCodes.Call, baseType.GetMethod("SomeMethodDefinedInBaseClassThatWasOverridenInThisDynamicType"));

The problem is that this calls the method on the base type and not the overriden method.

Is there any way I can get a reference to a methodbuilder only having a reference to the typebuilder that defined it? Or is there a way to call a method using ILGenerator without having to pass the 'MethodInfo' object to it?

© Stack Overflow or respective owner

Related posts about cil

Related posts about ilgenerator