Reputation: 1358
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?
Upvotes: 2
Views: 215
Reputation: 15559
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;
Upvotes: 2
Reputation: 144136
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 }));
Upvotes: 4