Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of List<T> from object

Tags:

c#

list

generics

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?

like image 275
3Pi Avatar asked Nov 01 '25 09:11

3Pi


1 Answers

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.

like image 65
Sergey Kalinichenko Avatar answered Nov 03 '25 23:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!