3Pi
3Pi

Reputation: 1914

Create List<> from runtime type

I am looking to create a List, where the type of T is several unrelated classes (with the same constructor arguments) that I know through reflection.

    DataBase = new ArrayList();
    foreach (Type T in Types)
    {
        DataBase.Add(new List<T>);
    }

Unfortunately, Visual Studio says that 'The type or namespace T could not be found'. Is there some way I can implement this, or cast a List to type T? Thanks, Peter

Upvotes: 15

Views: 26574

Answers (3)

GGulati
GGulati

Reputation: 1035

You could... use List<object> (if you know that your type is a reference type, or boxing is acceptable); or create a List via reflection.

Upvotes: 0

doogle
doogle

Reputation: 3406

You're confusing types and the System.Type class for Generic Type Parameters, here is the code to implement it the way you want:

var lt = typeof(List<>);
foreach (Type T in Types)
{
    var l = Activator.CreateInstance(lt.MakeGenericType(T));
    DataBase.Add(l);
}

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160892

You can use reflection:

List<object> database = new List<object>();
foreach (Type t in Types)
{
   var listType = typeof(List<>).MakeGenericType(t);
   database.Add(Activator.CreateInstance(listType));
}

Upvotes: 25

Related Questions