Monday, January 17, 2011

How to create generic type

Just a side note.

If you need to create a generic type having only Type object of the generic argument, you could do this (e.g. we need to create List of some objects):

public IEnumerable CreateList(Type elementType, int capacity)
{
    Type listType = typeof(List<>).CreateGenericType(elementType);
    return (IEnumerable)Activator.CreateInstance(listType, capacity);
}

Note, that you cannot return List<T> because you do not actually have compile-time type List<T>. So you need to cast the result of Activator.CreateInstance to some non-generic type.

No comments:

Post a Comment