Simon
Simon

Reputation: 25983

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?

Upvotes: 9

Views: 1821

Answers (3)

Marco Alves
Marco Alves

Reputation: 2856

My generic contribution that checks if a given type (or its base classes) implements an interface of type T:

public static bool ImplementsInterface(this Type type, Type interfaceType)
{
    while (type != null && type != typeof(object))
    {
        if (type.GetInterfaces().Any(@interface => 
            @interface.IsGenericType
            && @interface.GetGenericTypeDefinition() == interfaceType))
        {
            return true;
        }

        type = type.BaseType;
    }

    return false;
}

Upvotes: 0

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

Can you do somethin with GetGenericArguments ?

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

(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);
    }
}

Upvotes: 12

Related Questions