Hi all,
Is it possible to create a new List<T>
where the T is dynamically set at runtime?
Cheers
Hi all,
Is it possible to create a new List<T>
where the T is dynamically set at runtime?
Cheers
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 using generic you can do something like this
var asd = METHOD<Button>();
List<t> METHOD<t>()
{
return new List<t>();
}
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. 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));
}