4
class A
{
    public static void M<T>() { ... }
}

...
Type type = GetSomeType();

Then I need to call A.M<T>() where type == typeof(T).
Reflection?

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
  • Yes, this is only possible using reflection. – CodesInChaos Jul 24 '11 at 08:45
  • possible duplicate of [What's the best way to instantiate a generic from its name?](http://stackoverflow.com/questions/130208/whats-the-best-way-to-instantiate-a-generic-from-its-name) – vgru Jul 24 '11 at 08:47
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – usr May 30 '14 at 17:01

2 Answers2

8

Yes, you need reflection. For example:

var method = typeof(A).GetMethod("M");
var generic = method.MakeGenericMethod(type);
generic.Invoke(null, null);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

Because the type is known at runtime you need to use reflection:

Type type = GetSomeType();
var m = typeof(A)
    .GetMethod("M", BindingFlags.Static | BindingFlags.Public)
    .MakeGenericMethod(type);
m.Invoke(null, null);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928