Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamicMethod with generic type parameters

Is it possible to define a DynamicMethod with generic type parameters? The MethodBuilder class has the DefineGenericParameters method. Does the DynamicMethod have a counterpart? For example is it possible to create method with a signature like the one given blow using DynamicMethod?

void T Foo<T>(T a1, int a2)
like image 693
Alex Avatar asked Apr 25 '09 09:04

Alex


2 Answers

This doesn't appear to be possible: as you've seen DynamicMethod has no DefineGenericParameters method, and it inherits MakeGenericMethod from its MethodInfo base class, which just throws NotSupportedException.

A couple of possibilities:

  • Define a whole dynamic assembly using AppDomain.DefineDynamicAssembly
  • Do generics yourself, by generating the same DynamicMethod once for each set of type arguments
like image 163
Tim Robinson Avatar answered Nov 14 '22 12:11

Tim Robinson


Actually there is a way, it's not exactly generic but you'll get the idea:

public delegate T Foo<T>(T a1, int a2);

public class Dynamic<T>
{
    public static readonly Foo<T> Foo = GenerateFoo<T>();

    private static Foo<V> GenerateFoo<V>()
    {
        Type[] args = { typeof(V), typeof(int)};

        DynamicMethod method =
            new DynamicMethod("FooDynamic", typeof(V), args);

        // emit it

        return (Foo<V>)method.CreateDelegate(typeof(Foo<V>));
    }
}

You can call it like this:

Dynamic<double>.Foo(1.0, 3);
like image 31
atomicode Avatar answered Nov 14 '22 12:11

atomicode