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?
NET framework provides generics to create classes, structures, interfaces, and methods that have placeholders for the types they use. Generics are commonly used to create type-safe collections for both reference and value types. The . NET framework provides an extensive set of interfaces and classes in the System.
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type.
You can't do it like that - the point of generics is mostly compile-time type-safety - but you can do it with reflection:
public Dictionary<Type, object> GenerateLists(List<Type> types)
{
Dictionary<Type, object> lists = new Dictionary<Type, object>();
foreach (Type type in types)
{
Type genericList = typeof(List<>).MakeGenericType(type);
lists.Add(type, Activator.CreateInstance(genericList));
}
return lists;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With