C #: create an instance of a list, given a type reference

Suppose in C #, myType is a reference to some Type . Using only myType , can I create a List of myType objects?

For example, in the code below, although it is erroneous, I would like to instantiate through

new List < myType > () .

 using System ; using System.Reflection ; using System.Collections.Generic ; class MyClass { } class MainClass { public static void Main ( string [] args ) { Type myType = typeof ( MyClass ) ; List < myType > myList = new List < myType > ( ) ; } } 
+4
source share
5 answers

You can do this with Reflection:

 Type typeList = typeof(List<>); Type actualType = typeList.MakeGenericType(myType); object obj = Activator.CreateInstance(actualType); 
+8
source

You can use reflection, but since the type of the returned list is unknown at compile time, code using the returned list must access the elements through the interface with little precision.

This will not lead to accelerated or supported code using just a list.

The best solution is to create a <interface> list where <interface> is the strongest common interface or base class of all types that you could add to the list at runtime. At least this way you won’t have to convert back and forth from the object when working with members of the list, and you will have some time checking to sort the things you put into the list.

+2
source

Is there any reason to use

List<myType>' instead of list`

In fact, you want to store objects whose type is unknown in compiletime in a collection (list).

I would say if you planned to make this production code, use either List or use inheritance, and save the list of base classes.

+1
source

This is not possible because myType not known at compile time, and you cannot manipulate this list in your code. You could use reflection though to create an array.

0
source

All Articles