views:

342

answers:

2

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?

+6  A: 

(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);
    }
}
Marc Gravell
Is GetInterfaces sufficiently recursive to mean you don't need to worry about going up the parent types?
Jon Skeet
@Jon: I think so, yes.
Marc Gravell
A: 

Can you do somethin with GetGenericArguments ?

Frederik Gheysels