Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out whether an object's type is a subclass of IEnumerable<T> for any value type T?

I need to validate an object to see whether it is null, a value type, or IEnumerable<T> where T is a value type. So far I have:

if ((obj == null) ||
    (obj .GetType().IsValueType))
{
    valid = true;
}
else if (obj.GetType().IsSubclassOf(typeof(IEnumerable<>)))
{
     // TODO: check whether the generic parameter is a value type.
}

So I've found that the object is null, a value type, or IEnumerable<T> for some T; how do I check whether that T is a value type?

like image 884
Simon Avatar asked Feb 04 '23 11:02

Simon


1 Answers

(edit - added value type bits)

You need to check all the interfaces it implements (note it could in theory implement IEnumerable<T> for multiple T):

foreach (Type interfaceType in obj.GetType().GetInterfaces())
{
    if (interfaceType.IsGenericType
        && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
    {
        Type itemType = interfaceType.GetGenericArguments()[0];
        if(!itemType.IsValueType) continue;
        Console.WriteLine("IEnumerable-of-" + itemType.FullName);
    }
}
like image 79
Marc Gravell Avatar answered Feb 06 '23 01:02

Marc Gravell