Is it impossible to use Generics dynamically? [duplicate]

You can’t do it like that – the point of generics is mostly compile-time type-safety – but you can do it with reflection:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        Type genericList = typeof(List<>).MakeGenericType(type);
        lists.Add(type, Activator.CreateInstance(genericList));
    }

    return lists;
}

Leave a Comment