I need to create at runtime instances of a class that uses generics, like class<T>, without knowing previously the type T they will have, I would like to do something like that:
public Dictionary<Type, object> GenerateLists(List<Type> types) { Dictionary<Type, object> lists = new Dictionary<Type, object>(); foreach (Type type in types) { lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */ } return lists; }
…but I can’t. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?
You can’t do it like that – the point of generics is mostly compile-time type-safety – but you can do it with reflection: