Dynamically Create a generic type for template

What you are looking for is MakeGenericType

string elementTypeName = Console.ReadLine();
Type elementType = Type.GetType(elementTypeName);
Type[] types = new Type[] { elementType };

Type listType = typeof(List<>);
Type genericType = listType.MakeGenericType(types);
IProxy  proxy = (IProxy)Activator.CreateInstance(genericType);

So what you are doing is getting the type-definition of the generic “template” class, then building a specialization of the type using your runtime-driving types.

Leave a Comment