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.
You can do it like this:
bool implements =
listType.GetInterfaces()
.Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof (ICollection<>));
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With