I am trying to create a list of a certain type.
I want to use the List notation but all I know is a "System.Type"
The type a have is variable. How can I create a list of a variable type?
I want something similar to this code.
public IList createListOfMyType(Type myType) { return new List<myType>(); }
To create the instance we should use System. Activator. CreateInstance(myType). But then again, the return value if an object of type myType.
A simple solution for constucting a List of Lists is to create the individual lists and use the List<T>. Add(T) method to add them to the main list. The following example demonstrates its usage. That's all about creating a List of Lists in C#.
Something like this should work.
public IList createList(Type myType) { Type genericListType = typeof(List<>).MakeGenericType(myType); return (IList)Activator.CreateInstance(genericListType); }
You could use Reflections, here is a sample:
Type mytype = typeof (int); Type listGenericType = typeof (List<>); Type list = listGenericType.MakeGenericType(mytype); ConstructorInfo ci = list.GetConstructor(new Type[] {}); List<int> listInt = (List<int>)ci.Invoke(new object[] {});
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