6

I need to use method like:

DoSomething<(T)>();

But i don't know which Type i have, only object of class Type. How can i call this method if I have only:

Type typeOfGeneric;
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
wassertim
  • 3,116
  • 2
  • 24
  • 39

2 Answers2

3

You use reflection (assuming DoSomething() is static):

var methodInfo = typeOfGeneric.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );

EDIT: Your question changes while I wrote the answer. The above code is for a non-generic method, here it is for a generic class:

var constructedType = someType.MakeGenericMethod( typeOfGeneric );
var methodInfo = constructedType.GetMethod( "DoSomething" );
methodInfo.Invoke( null, null );

And here it is for a static generic method on a non-generic class:

var typeOfClass = typeof(ClassWithGenericStaticMethod);

MethodInfo methodInfo = typeOfClass.GetMethod("DoSomething",   
    System.Reflection.BindingFlags.Static | BindingFlags.Public);

MethodInfo genericMethodInfo = 
    methodInfo.MakeGenericMethod(new Type[] { typeOfGeneric });

genericMethodInfo.Invoke(null, new object[] { "hello" });
LBushkin
  • 129,300
  • 32
  • 216
  • 265
1

If you only have a Type specified as a Type, you'd have to build the generic method, and call it via reflection.

Type thisType = this.GetType(); // Get your current class type
MethodInfo doSomethingInfo = thisType.GetMethod("DoSomething");

MethodInfo concreteDoSomething = doSomethingInfo.MakeGenericMethod(typeOfGeneric);
concreteDoSomething.Invoke(this, null);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373