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)
3
  • 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, 2009 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, 2009 at 17:45
  • 1
    See: visualstudio.uservoice.com/forums/121579-visual-studio/… to vote on having support added.
    – cdiggins
    Jul 10, 2014 at 16:02

2 Answers 2

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
1
  • 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, 2009 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);
1
  • 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, 2014 at 12:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.