How do I tell whether a Type implements IList<>?
In fact, you cannot have an instance of a generic type definition. Therefore, the IsAssignableFrom() method works as expected. To achieve what you want, do the following:
public bool IsGenericList(Type type)
{
if (type == null) {
throw new ArgumentNullException("type");
}
foreach (Type @interface in type.GetInterfaces()) {
if (@interface.IsGenericType) {
if (@interface.GetGenericTypeDefinition() == typeof(ICollection<>)) {
// if needed, you can also return the type used as generic argument
return true;
}
}
}
return false;
}
Just out of curiosity, what do you need this for?
I too want to test if a type implements IList<T>
for some T. I made the obvious change to Lucero's answer but it caused a subtle bug not present in the original answer. Here's my final edit:
/// <summary>
/// Test if a type derives from IList of T, for any T.
/// </summary>
public bool TestIfGenericList(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
var interfaceTest = new Predicate<Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>));
return interfaceTest(type) || type.GetInterfaces().Any(i => interfaceTest(i));
}