Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if type implements ICollection<T>

How can I check if a given type is an implementation of ICollection<T>?

For instance, let's say we have the following variable:

ICollection<object> list = new List<object>();
Type listType = list.GetType();

Is there a way to identify if listType is a generic ICollection<>?

I have tried the following, but with no luck:

if(typeof(ICollection).IsAssignableFrom(listType))
       // ...

if(typeof(ICollection<>).IsAssignableFrom(listType))
      // ...

Of course, I can do the following:

if(typeof(ICollection<object>).IsAssignableFrom(listType))
     // ...

But that will only work for ICollection<object> types. If I have an ICollection<string> it will fail.

like image 725
Matias Cicero Avatar asked Oct 05 '15 00:10

Matias Cicero


2 Answers

You can do it like this:

bool implements = 
    listType.GetInterfaces()
    .Any(x =>
        x.IsGenericType &&
        x.GetGenericTypeDefinition() == typeof (ICollection<>));
like image 64
Yacoub Massad Avatar answered Oct 21 '22 00:10

Yacoub Massad


You can try use this code, it works for all collection type

    public static class GenericClassifier
    {
        public static bool IsICollection(Type type)
        {
            return Array.Exists(type.GetInterfaces(), IsGenericCollectionType);
        }

        public static bool IsIEnumerable(Type type)
        {
            return Array.Exists(type.GetInterfaces(), IsGenericEnumerableType);
        }

        public static bool IsIList(Type type)
        {
            return Array.Exists(type.GetInterfaces(), IsListCollectionType);
        }

        static bool IsGenericCollectionType(Type type)
        {
            return type.IsGenericType && (typeof(ICollection<>) == type.GetGenericTypeDefinition());
        }

        static bool IsGenericEnumerableType(Type type)
        {
            return type.IsGenericType && (typeof(IEnumerable<>) == type.GetGenericTypeDefinition());
        }

        static bool IsListCollectionType(Type type)
        {
            return type.IsGenericType && (typeof(IList) == type.GetGenericTypeDefinition());
        }
    }
like image 20
Kien Chu Avatar answered Oct 21 '22 02:10

Kien Chu