GetMethod limitation regarding Generics

I've got several inquiry emails about this issue, so I think it is a good idea to publish the problem here.

Say we have:

public class Test

{
public void Teste<U>(U teste, int i) { Console.WriteLine(teste); }

   public void Teste<U> (U teste) { }

}

Is it possible to use GetMethod to get void Teste<U>(U teste, int i)out?

Unfortunately, the answer is there is no way for now to use only GetMethod to get the method before we know the type of U.  It is a limitation in Reflection for Whidbey.

Here is a possible workaround for you, you can use GetMembers to minimize the methodinfo you have to retrieve.

using System;
using System.Reflection;

public class Test
{
public void Teste<U>(U teste, int i) { Console.WriteLine(teste); }

    public void Teste<U> (U teste) { }

    public static void Main()
{

MemberInfo[] mis = typeof(Test).GetMember("Teste*", BindingFlags.InvokeMethod|BindingFlags.Public|BindingFlags.Instance);
if (mis.Length == 0) {Console.WriteLine("No Teste Methods"); return;}

        Type U = ((MethodInfo)mis[0]).GetGenericArguments()[0]; // assume we know the class structure above, for simplicity.
MethodInfo mInfo = typeof(Test).GetMethod("Teste", new Type[] { U, typeof(int) });

        if (mInfo.IsGenericMethod)
{
mInfo = mInfo.MakeGenericMethod(typeof(string));
mInfo.Invoke(new Test(), new object[] { "Test - calling generic method", 1 });
}
}
}

Comments

  • Anonymous
    September 14, 2005
    The comment has been removed