3Pi
3Pi

Reputation: 1914

Get type of List<T> from object

I have a List of Lists, with each list holding a different class of object. To add elements to the correct list, I need to be able to find the type of the list. I am currently trying to accomplish it in this way:

        foreach(object o in DataBase)
        {
            Type t = o.GetType();
            if (t != typeof(T))
                continue;
            else
            {
                List<T> L = (List<T>)o;
                L.Add(element);
                break;
            }
         }

However, this returns a List Type, of System.Collections.Generic.List`1[[myType,etc,etc]]. Is there a way to extract 'myType' from the type of List, for a proper comparison?

Upvotes: 4

Views: 2536

Answers (2)

drf
drf

Reputation: 8709

Without explicitly checking the generic argument type, you may be able to refactor the above code as:

foreach(object o in DataBase)
    if (o is List<T>)
    {
        (o as List<T>).Add(element)
        break;
    }

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

Use GetGenericArguments method:

Type listTypeParam = myListType.GetGenericArguments()[0];

Since myListType is an instance of a generic type with exactly one type parameter, the type T will be returned in the 0-th position of the returned array.

Upvotes: 7

Related Questions