Tag Archives: Generics

How to create a dynamic collection in C#

problem:

I need to instantiate many collections. How can I do this dynamically with reflection?

answer:

Use the typeof to get the type of your collection and what kind of collection it will become. Pass those as parameters to a custom method to convert your parameters into a collection using “MakeGenericType” for your collection type and pass in the parameter of what object the collection should contain. Now use C#’s Activator class to create an instance of your collection and return it.

class Program
{
    static void Main(string[], args)
    {
        var myList = CreateCollection(typeof(List<>), typeof(Employee));
        // do more stuff here ...
    }

    private static object CreateCollection(Type collectionType, Type iteType)
    {
        var closedType = collectionType.MakeGenericType(itemType);
        return Activator.CreateInstance(closedType);
    }
}