Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic List<T> type [duplicate]

Tags:

c#

.net

dynamic

Is it possible to create a new List<T> where the T is dynamically set at runtime?

Cheers

like image 207
AndrewC Avatar asked Mar 18 '10 23:03

AndrewC


3 Answers

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);
like image 141
Dan Bryant Avatar answered Oct 22 '22 21:10

Dan Bryant


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);
}
like image 9
Reed Copsey Avatar answered Oct 22 '22 20:10

Reed Copsey


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));
    }
like image 1
Jason Kresowaty Avatar answered Oct 22 '22 19:10

Jason Kresowaty