3

I have a string containing the name of a generic class with specified type:

string s = "GenericRouteHandler<MemberHandler>";

How do I instantiate an instance from this string? I know how to instantiate a concrete class using Type.GetType() and then use Activator but I am not sure where to go with a generic class.

Andrey
  • 20,487
  • 26
  • 108
  • 176

1 Answers1

2

Like this typeof(GenericRouteHandler<>).MakeGenericType(typeof(MemberHandler));

Of course if you don't have the types you have to use Type.GetType(string) to get the type instead of typeof.

EDIT: Then you have to activate the type Activator.CreateInstance() or invoke a contructor if know the signature myGenericType.GetConstructor(ctorArgsTypes).Invoke(ctorParams); ; it can be faster if cache the consturctors it can be faster then Activator.CreateInstance()

msdn

user44298
  • 910
  • 7
  • 20