Reputation: 845
Is it possible to mix generics with Type arguments? For example, is there a way to write code like this:
IList GetListOfListsOfTypes(Type[] types)
{
IList<IList> listOfLists = new List<IList>();
foreach (Type t in types)
{
listOfLists.Add(new List<t>());
}
return listOfLists.ToList();
}
Clearly, the compiler does not like this, but is there some way to achieve this?
Upvotes: 1
Views: 64
Reputation: 164281
To do it with reflection, you must construct the closed generic type from the open type; then construct it with one of the options we have for that with reflection. Activator.CreateInstance works well for that:
IList GetListOfListsOfTypes(Type[] types)
{
IList<IList> listOfLists = new List<IList>();
foreach (Type t in types)
{
Type requestedTypeDefinition = typeof(List<>);
Type genericType = requestedTypeDefinition.MakeGenericType(t);
IList newList = (IList)Activator.CreateInstance(genericType);
listOfLists.Add(newList);
}
return listOfLists;
}
Just be aware that you are returning a list of non-generic IList
s from this method, which is necessary since we don't know the types at compile time, so in order to use your new generic lists, you probably need to use reflection again. Consider if it's worth it - of course, it depends on your requirements.
Upvotes: 4