Suppose that, in C#, myType
is a reference to some Type
.
Using myType
only, is it possible to create a List
of objects of myType
?
For example, in the code below, although it is erroneous, I'd like to instantiate via
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 > ( ) ;
}
}
You can do so using Reflection:
Type typeList = typeof(List<>);
Type actualType = typeList.MakeGenericType(myType);
object obj = Activator.CreateInstance(actualType);
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