Search code examples
c#reflectiongenericsmethodinfo

referencing desired overloaded generic method


given

public Class Example
{

public static void Foo< T>(int ID){}

public static void Foo< T,U>(int ID){}

}

Questions:

  1. Is it correct to call this an "overloaded generic method"?
  2. How can either method be specified in creation of a MethodInfo object?

    Type exampleType = Type.GetType("fullyqualifiednameOfExample, namespaceOfExample");
    MethodInfo mi = exampleType.GetMethod("Foo", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof(Type), typeof(Type) }, null);
    

argument 4 causes the compiler much displeasure


Solution

  • I can't find a way of using GetMethod that would do what you want. But you can get all the methods and go through the list until you find the method that you want.

    Remember you need to call MakeGenericMethod before you can actually use it.

    var allMethods = typeof (Example).GetMethods(BindingFlags.Public | BindingFlags.Static);
    MethodInfo foundMi = allMethods.FirstOrDefault(
        mi => mi.Name == "Foo" && mi.GetGenericArguments().Count() == 2);
    if (foundMi != null)
    {
        MethodInfo closedMi = foundMi.MakeGenericMethod(new Type[] {typeof (int), typeof (string)});
        Example example= new Example();
        closedMi.Invoke(example, new object[] { 5 });
    }