How to call a generic method with a given type object?

I want to call my generic method with a given type object.

void Foo(Type t) { MyGenericMethod<t>(); } 

obviously not working.

How can I make it work?

+45
generics reflection c # types
Sep 10 '09 at 22:47
source share
3 answers

Your sample code will not work because the generic method expects a type identifier, not an instance of the Type class. For this you need to use reflection:

 public class Example { public void CallingTest() { MethodInfo method = typeof (Example).GetMethod("Test"); MethodInfo genericMethod = method.MakeGenericMethod(typeof (string)); genericMethod.Invoke(this, null); } public void Test<T>() { Console.WriteLine(typeof (T).Name); } } 

Keep in mind that this is very fragile, I would prefer to find another template to call your method.

Another hacky solution (maybe someone can make it a little cleaner) would be to use some expression magic:

 public class Example { public void CallingTest() { MethodInfo method = GetMethod<Example>(x => x.Test<object>()); MethodInfo genericMethod = method.MakeGenericMethod(typeof (string)); genericMethod.Invoke(this, null); } public static MethodInfo GetMethod<T>(Expression<Action<T>> expr) { return ((MethodCallExpression) expr.Body) .Method .GetGenericMethodDefinition(); } public void Test<T>() { Console.WriteLine(typeof (T).Name); } } 

Note the passing of an identifier of type "object" as an argument of a generic type to lambda. Failed to figure out how to get around this so quickly. In any case, I think it is safe to compile. He somehow feels wrong: /

+46
Sep 10 '09 at 22:56
source share

You need to use reflection, unfortunately (for the reasons Jared talked about). For example:

 MethodInfo method = typeof(Foo).GetMethod("MyGenericMethod"); method = method.MakeGenericMethod(t); method.Invoke(this, new object[0]); 

Obviously you need more error checking :)




Lateral note: my local MSDN does not indicate that the parameter from MakeGenericMethod is an array of parameters, so I expected what would be needed:

 method = method.MakeGenericMethod(new Type[] { t }); 

but it looks like it's an array of parameters in reality, and the MSDN online docs agree. Odd

+15
Sep 10 '09 at 22:51
source share

This approach will not work. The reason is because Type is an object whose type is determined at runtime. However, you are trying to use it to call a generic method. At compile time, the general type of method call is set. Therefore, a type object can never be used for a type parameter for a general method.

-one
Sep 10 '09 at 10:50
source share



All Articles