Mike Mike - 1 year ago 86
C# Question

ILGenerator instantiate object and call instance method

I am new to ILGenerator so bare with me and direct me to any answers that may help. Thanks.

I am trying to construct an instance of a generic type and call a method on that instance. Then return the result of the method.

var genericType = typeof(GenericType<>).MakeGenericType(typeof(TOutput));
var instanceMethod = genericType.GetMethod("MethodName", new Type[0]);
il.Emit(OpCodes.Call, instanceMethod);

I keep getting a 'System.InvalidProgramExecution' exception.

GenericType class looks like this

public class GenericType<T>
public T MethodName()

Answer Source

Try this code:

var il = mbuilder.GetILGenerator();
var genericType = typeof(GenericType<>).MakeGenericType(typeof(TOutput));
il.Emit(OpCodes.Newobj, genericType.GetConstructor(Type.EmptyTypes));
il.EmitCall(OpCodes.Callvirt, genericType.GetMethod("MethodName", Type.EmptyTypes), null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download