2

I'm trying to use reflection to get a specific MethodInfo of a class, but am unsure how to differentiate between the two following methods:

public class Test
{
    public IBar<T1> Foo<T1>();
    public IBar<T1, T2> Foo<T1, T2>();
}

How can I get a reference to the different Foo methods, assuming I know the number of type parameters? Just calling typeof(Test).GetMethod("Foo") will throw an exception that the method name is ambiguous and there aren't a differing number of parameters to check.

Brian Vallelunga
  • 9,869
  • 15
  • 60
  • 87

1 Answers1

5

You could get all methods then filter them based on generic argument count:

typeof(Test).GetMethods()
.First(x => x.Name == "Foo" && x.GetGenericArguments().Length == 2);

Note that First method will throw an exception if there is no method that satisfies the condition.You can use FirstOrDefault and check for null instead if you want to avoid exceptions.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184