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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With