Wisher78
Wisher78

Reputation: 61

Expression.Call with MethodInfo and generic type arguments

How can I use Expression.Call with MethodInfo and generic type arguments? Only the overloading with methodName has typeArguments.

var methodInfo = typeof(MyClass).GetMethod("OutputTypeName");          
var expression = Expression.Call(methodInfo);
Expression.Lambda<Action>(expression).Compile()();

public static class MyClass
{
    public static void OutputTypeName<T>()
    {
        Console.WriteLine("Type: " + typeof(T).Name);
    }
}

Upvotes: 2

Views: 790

Answers (1)

Jotrius
Jotrius

Reputation: 657

You can use MethodInfo.MakeGenericMethod:

var methodInfo = typeof(MyClass).GetMethod("OutputTypeName");
var genericMethodInfo = methodInfo.MakeGenericMethod(typeof(int));
var expression = Expression.Call(genericMethodInfo);
...

Upvotes: 2

Related Questions