If object is Generic List


Question

Is there any way to determine if an object is a generic list? I'm not going to know the type of the list, I just know it's a list. How can I determine that?

1
14
10/30/2008 12:21:32 AM

Accepted Answer

This will return "True"

List<int> myList = new List<int>();

Console.Write(myList.GetType().IsGenericType && myList is IEnumerable);

Do you care to know if it's exactly a "List"... or are you ok with it being IEnumerable, and Generic?

23
10/30/2008 12:32:03 AM

The following method will return the item type of a generic collection type. If the type does not implement ICollection<> then null is returned.

static Type GetGenericCollectionItemType(Type type)
{
    if (type.IsGenericType)
    {
        var args = type.GetGenericArguments();
        if (args.Length == 1 &&
            typeof(ICollection<>).MakeGenericType(args).IsAssignableFrom(type))
        {
            return args[0];
        }
    }
    return null;
}

Edit: The above solution assumes that the specified type has a generic parameter of its own. This will not work for types that implement ICollection<> with a hard coded generic parameter, for example:

class PersonCollection : List<Person> {}

Here is a new implementation that will handle this case.

static Type GetGenericCollectionItemType(Type type)
{
    return type.GetInterfaces()
        .Where(face => face.IsGenericType &&
                       face.GetGenericTypeDefinition() == typeof(ICollection<>))
        .Select(face => face.GetGenericArguments()[0])
        .FirstOrDefault();
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon