Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if object derives from collection type

I want to determine if a generic object type ("T") method type parameter is a collection type. I would typically be sending T through as a Generic.List but it could be any collection type as this is used in a helper function.

Would I be best to test if it implements IEnumerable<T>?

If so, what would the code look like?

Update 14:17 GMT+10 Possibly extending on a solution here (however only works for List<T>'s not IEnumerable<T>'s when it should if List derives ?)

T currentObj;    
// works if currentObj is List<T>
currentObj.GetType().GetGenericTypeDefinition() == typeof(List<>)
// does not work if currentObj is List<T>
currentObj.GetType().GetGenericTypeDefinition() == typeof(IEnumerable<>)
like image 319
GONeale Avatar asked Sep 06 '25 13:09

GONeale


2 Answers

This will be the simplest check..

if(Obj is ICollection)
{
    //Derived from ICollection
}
else
{
    //Not Derived from ICollection
}
like image 159
this. __curious_geek Avatar answered Sep 09 '25 06:09

this. __curious_geek


You can use Type.GetInterface() with the mangled name.

private bool IsTAnEnumerable<T>(T x)
{
    return null != typeof(T).GetInterface("IEnumerable`1");
}
like image 29
Jonathan Rupp Avatar answered Sep 09 '25 07:09

Jonathan Rupp