tags:

views:

63

answers:

2

I am trying to create a list of a certain type.

I want to use the List notation but all I know is a "System.Type"

The type a have is variable. How can I create a list of a variable type?

I want something similar to this code.

public IList createListOfMyType(Type myType)
{
     return new List<myType>();
}
+3  A: 

You could use Reflections, here is a sample:

    Type mytype = typeof (int);

    Type listGenericType = typeof (List<>);

    Type list = listGenericType.MakeGenericType(mytype);

    ConstructorInfo ci = list.GetConstructor(new Type[] {});

    List<int> listInt = (List<int>)ci.Invoke(new object[] {});
Andrew Bezzub
+1  A: 

Something like this should work.

public IList createList(Type myType)
{
    Type genericListType = typeof(List<>).MakeGenericType(myType);
    return (IList)Activator.CreateInstance(genericListType);
}
smencer
Thanks, this solved my problem.
Jan