Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a type is a type of collection?

I am trying to determine if a runtime type is some sort of collection type. What I have below works, but it seems strange that I have to name the types that I believe to be collection types in an array like I have done.

In the code below, the reason for the generic logic is because, in my app, I expect all collections to be generic.

bool IsCollectionType(Type type) {     if (!type.GetGenericArguments().Any())         return false;      Type genericTypeDefinition = type.GetGenericTypeDefinition();     var collectionTypes = new[] { typeof(IEnumerable<>), typeof(ICollection<>), typeof(IList<>), typeof(List<>) };     return collectionTypes.Any(x => x.IsAssignableFrom(genericTypeDefinition)); } 

How would I refactor this code to be smarter or simpler?

like image 586
Byron Sommardahl Avatar asked Jun 02 '12 17:06

Byron Sommardahl


People also ask

How do you check if an object is an array C#?

To do this task, we use the IsArray property of the Type class. This property is used to determine whether the specified type is an array or not. IsArray property will return true if the specified type is an array. Otherwise, it will return false.


1 Answers

Really all of these types inherit IEnumerable. You can check only for it:

bool IsEnumerableType(Type type) {     return (type.GetInterface(nameof(IEnumerable)) != null); } 

or if you really need to check for ICollection:

bool IsCollectionType(Type type) {     return (type.GetInterface(nameof(ICollection)) != null); } 

Look at "Syntax" part:

  • List<T>

  • IList

  • ICollection

like image 96
Ruben Avatar answered Sep 20 '22 00:09

Ruben