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

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.