8

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)
svick
  • 236,525
  • 50
  • 385
  • 514
Alex
  • 2,040
  • 2
  • 19
  • 29
  • 1
    If you are dynamically creating the method then wouldn't you know the types when you generate the method? Which would remove the need to have a generic dynamic method? – Steven Apr 25 '09 at 13:29
  • I'm writing a little interpreter and I want to use DynamicMethods to compile the functions. The language has support for parametric polymorphism and it would have been nice to use type parameters and not have to generate overloads for each parameter combination. – Alex Apr 25 '09 at 17:45
  • 1
    See: https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2508820-dynamicmethod-to-support-generic-type-parameters-l to vote on having support added. – cdiggins Jul 10 '14 at 16:02

2 Answers2

7

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
Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
  • Thanks. That's what I was afraid of. I guess there's no other way. Though it would be nice to have support for this with DynamicMethods. – Alex Apr 25 '09 at 17:43
4

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);
atomicode
  • 581
  • 4
  • 11
  • Actually, that's no a bad idea :). I'll keep it in mind if I ever face this issue again. I'm also selecting your reply as an answer since it gets close to solving the original problem. Thanks. – Alex Mar 26 '14 at 12:44