Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : instantiate a List, given a reference to a Type [duplicate]

Tags:

c#

list

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 > ( ) ;

        }

    }
like image 861
JaysonFix Avatar asked Dec 17 '22 06:12

JaysonFix


1 Answers

You can do so using Reflection:

Type typeList = typeof(List<>);
Type actualType = typeList.MakeGenericType(myType);
object obj = Activator.CreateInstance(actualType);
like image 59
Andy Avatar answered Jan 25 '23 23:01

Andy