Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create List<> from runtime type

Tags:

c#

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

like image 447
3Pi Avatar asked Jan 20 '12 00:01

3Pi


People also ask

How to create List dynamically in c#?

Firstly, you need to create an instance of a concrete type. You're taking a non-generic interface ( IList ) and trying to create a generic type from it. You need typeof(List<>) . Secondly, you're calling AddItem which isn't a method on IList .

How do you create a list variable type?

Select a list Type. To create a list of a simple type, select one of the types shown. To create a list of a complex type, from Type select Complex Variable and from Complex Variable Type select the complex type, for example, Timer.


1 Answers

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));
}
like image 69
BrokenGlass Avatar answered Oct 07 '22 23:10

BrokenGlass