Is it possible to create a new List<T>
where the T is dynamically set at runtime?
Cheers
It's possible, but not necessarily useful, since you couldn't actually use it from compiled code as strongly typed. The creation code would be
Type myType;
Type listType = typeof(List<>).MakeGenericType(myType);
IList myList = (IList)Activator.CreateInstance(listType);
Yes. You can do this via Reflection, using Type.MakeGenericType and Activator.CreateInstance.
IList MakeListOfType(Type listType)
{
Type listType = typeof(List<>);
Type specificListType = listType.MakeGenericType(listType);
return (IList)Activator.CreateInstance(specificListType);
}
Yes. However, you won't be able to assign it to a variable that has a generic type since the T in this case will not be decided until runtime. (If you are thinking that the .NET 4.0 covariance feature will help you and let you declare the variable as IList<SomeSuperType>
, it won't as the T
is used by List<T>
for both in
and out
purposes.)
Note the unusual List<> syntax in order to access the "unconstructed" generic type.
public static System.Collections.IList ConstructGenericList(Type t)
{
return (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(t));
}
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