Yes, you can instantiate a generic class with a type known only at run time, for example:
public class A { } public class U<T> { public TX { get; set; } } static void Main(string[] args) { Type a = typeof(A); Type u = typeof(U<>); dynamic uOfA = Activator.CreateInstance(u.MakeGenericType(a)); uOfA.X = new A(); Console.WriteLine(uOfA.GetType()); Console.WriteLine(uOfA.X.GetType()); }
However, this snippet uses reflection and dynamic typing, which can cause many maintenance problems, so you would be better off using them very carefully or finding a simpler solution.
source share