5

Is it possible to use generics with the IL Generator?

        DynamicMethod method = new DynamicMethod(
            "GetStuff", typeof(int), new Type[] { typeof(object) });

        ILGenerator il = method.GetILGenerator();

        ... etc
svick
  • 236,525
  • 50
  • 385
  • 514
sgtz
  • 8,849
  • 9
  • 51
  • 91
  • 1
    possible duplicate of [DynamicMethod with generic type parameters](http://stackoverflow.com/questions/788618/dynamicmethod-with-generic-type-parameters) – Roman Starkov Mar 21 '12 at 19:36
  • It's not clear from your question: do you want to create a generic method or just use some generic type (or method) inside it? – svick Mar 21 '12 at 20:12
  • @svick: I want to dynamically create a generic method. – sgtz Mar 21 '12 at 20:31
  • @romkyns: I read that question & answer previously while digging through the SO material. I made an effort to ensure it wasn't a duplicate, but I took a chance in asking the question again as it looked like that information might be for a previous version of .net. – sgtz Mar 21 '12 at 20:34

1 Answers1

8

Yes, it is possible, but not with the DynamicMethod class. If you are restricted to using this class, you're out of luck. If you can instead use a MethodBuilder object, read on.

Emitting the body of a generic method is, for most intents and purposes, no different from emitting the body of other methods, except that you can make local variables of the generic types. Here is an example of creating a generic method using MethodBuilder with the generic argument T and creating a local of type T:

MethodBuilder method;
//... Leaving out code to create MethodBuilder and store in method
var genericParameters = method.DefineGenericParameters(new[] { "T" });
var il = method.GetILGenerator();
LocalBuilder genericLocal = il.DeclareLocal(genericParameters[0]);

To emit a call to that generic method from another method, use this code. Assuming method is a MethodInfo or MethodBuilder object that describes a generic method definition, you can emit a call to that method with the single generic parameter int as follows:

il.EmitCall(OpCodes.Call, method.MakeGenericMethod(typeof(int)), new[] { typeof(int) }));
leviathanbadger
  • 1,682
  • 15
  • 23
  • 1
    Instead of calling `GetGenericArguments()` you can use the array returned by `DefineGenericParameters()`. – svick Mar 21 '12 at 20:13
  • Thanks @svick & aboveyouOO. I read on SO that it wasn't possible, and thought to ask anyway -- I hoped that that info might have been for a previous version of .net – sgtz Mar 21 '12 at 20:29