Search code examples
c#.netsystem.reflection

Using a string value as a generic type parameter


Let's say I have a method that looks like this:

public bool Execute<T>()
 {
 }

...and I have a string variable that describes the class name of the type I need to pass in, like

string typeName = "Person"

I've naively tried

var typeDef = Type.GetType(typeName);
 Execute<typeDef>();

, but that's a no-go. Is there a programatic way of passing in a generic type parameter when all I have is the class name in a string?


Solution

  • var typeDef = Type.GetType(typeName);
    var ret = (bool)this.GetType().GetMethod(nameof(Execute)).MakeGenericMethod(typeDef).Invoke(this, new object[0])