tags:

views:

149

answers:

2

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;
+1  A: 

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
I think you did not get my question. How to pass Type object as generic parameter?
Tim
A: 

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