views:

121

answers:

2

In C# I want to create a list based on a dynamic value type, e.g.:

void Function1() {

  TypeBuilder tb = ....   // tb is a value type
  ...
  Type myType = tb.CreateType();
  List<myType> myTable = new List<myType>();
}

void Function2(Type myType)
{
  List<myType> myTable = new List<myType>();
}

This won't comple because List<> wants a staticly defined type name. Is there any way to work around this?

+4  A: 

You can create a strongly-typed list at runtime through reflection although you can only access it through the non-generic IList interface

IList myTable = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new[] { myType }));
Lee
This requires using System.Collectionsto compile.
Max Yaffe
+2  A: 

You are going to have to use reflection to create the list:

Type listType = typeof(List<>);
Type concreteType = listType.MakeGenericType(myType);

IList list = Activator.CreateInstance(concreteType) as IList;
dkackman
This requires using System.Collectionsto compile.
Max Yaffe