Search code examples
c#generic-methodgenerics

How can I send Type variable to the method which is generic?


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.

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.