Question

I have a method like this,

public List<T> Test<T>()
{
    // do something.
}

I don't know what is T and dont have. But I have type of T as TYPE.

for example:

class Person
{

}

var type = typeof(Person);

I don't have Person. Person is keeping at the type object.

How can I use the test method ?

var list = Test<type>(); // It gives an error like this. I must use the type object.
Was it helpful?

Solution

You can use the MakeGenericMethod method from MethodInfo:

MethodInfo info = this.GetType().GetMethod("Test").MakeGenericMethod(type);
object result = info.Invoke(this, null);

This is assuming you call the method inside the same type that defines Test. If you call it from somewhere else, use typeof(ClassThatDefinesTest) instead of this.GetType(), and the instance of this class instead of this.

OTHER TIPS

If typeof(T) is all you really needed, then you can refactor it to:

public void Test(Type t)
{
    // do something.
}

And call it like:

Test(type);

If this won't work for you, I recommend Botz3000's solution using MakeGenericMethod.

You could expose both Test<T>() and Test(Type) and then have one call the other, (either with MakeGenericMethod or typeof(T)) depending on whether you need the static type or simply the runtime type. That way your callers don't need to know which of the two you need.

You have pass the Class name to it. Please refer to the following MSDN,

http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.100).aspx

As said @Botz3000 you can use MakeGenericMethod() method. But another solution could be use the dynamic keyword and the CreateInstance() method from Activator class:

public void Test(Type type)
{
    dynamic myVariable = Activator.CreateInstance(type);          
    // do something, like use myVariable and call a method: myVariable.MyMethod(); ...
}

You call it like this:

Test<Person>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top