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
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 .
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With