Alex Rivera | Logout

How to tell whether a Type is a list or array or IEnumerable or

Asked 2010-11-07T00:46:01.523
45

What's the easiest way, given a Type object, to test to see whether it is actually a list of objects? I.e. Array or IEnumerable/IEnumerable<>.

Edit
Report

1 Answer

-10

Simple. The easiest thing to do is the following:

IList<T> listTest = null;

try{
     listTest = ((IList<T>)yourObject);
}
catch(Exception listException)
{
    //your object doesn't support IList and is not of type List<T>
}

IEnumerable<T> enumerableTest = null;

try{
     enumerableTest = ((IEnumerable<T>)yourObject);
}
catch(Exception enumerableException)
{
     //your object doesn't suport IEnumerable<T>;
}

==================================================

You can also try this which doesn't involve multiple try/catch blocks. It's better if you can avoid using those because each condition is actually evaluated by the runtime during runtime... it's bad code (though sometimes there's no way around it).

Type t = yourObject.GetType();

if( t is typeof(List<OjbectType>) )   //object type is string, decimal, whatever...
{
     // t is of type List<ObjectType>...
}
else if( t is typeof(IEnumerable<ObjectType>)
{
     // t is of type IEnumerable<ObjectType>...
}
else
{
    // t is some other type.
    // use reflection to find it.
}
answered 2010-11-07T03:36:39.507

Your Answer