1

Assuming that I have a third party class Foo with a signature like this:

void Execute<T>();
void Execute(string[] args);

Instead of calling

Execute<Bar>();

I need to use the qualified name of the Bar classe to invoke the generic method. Example:

Type barType = Type.GetType("Program.Bar");
Execute<barType>();

I've already tried some answers I found on other threads but all of them gave me issues. For instance, I can't use the GetMethod("Execute") since it throws an ambiguous excpetion.

nunob
  • 592
  • 7
  • 24
  • It sounds like you want to dynamically invoke the generic method based on a `Type`. If so, see this question: https://stackoverflow.com/questions/325156/calling-generic-method-with-a-type-argument-known-only-at-execution-time – test Dec 11 '15 at 17:39

2 Answers2

1

You can run it like this:

class A 
{
    public void Execute<T>() { }
    public void Execute(string[] args) { }
}

var method = typeof(A).GetMethods().FirstOrDefault(
    m => m.Name == "Execute" 
    && !m.GetParameters().Any()
    && m.GetGenericArguments().Count() == 1
    );

Type barType = Type.GetType("Program.Bar");

method.MakeGenericMethod(barType).Invoke();

You can either change FirstOrDefault to First, or add some error handling if null is expected (depends on your use case).

Rob
  • 26,989
  • 16
  • 82
  • 98
  • Any reason not to use `Type.GetMethod(string, Type[])` instead of enumerating all methods? – Yuval Itzchakov Dec 11 '15 at 18:50
  • 1
    @YuvalItzchakov Yep - because we want to find a method with exactly one generic argument (If for example, there was a `void Execute() { }` overload) – Rob Dec 12 '15 at 06:56
0

Type parameters have to be known at compile time, so in order to call the method directly, you will need to either wrap the type or change the signature to take in a type.

Otherwise, you will need to use reflection to invoke the method by name.

moarboilerplate
  • 1,633
  • 9
  • 23