Checking if Type or instance implements IEnumerable regardless of Type T
In addition to Type.IsAssignableFrom(Type)
, you can also use Type.GetInterfaces()
:
public static bool ImplementsInterface(this Type type, Type interfaceType)
{
// Deal with the edge case
if ( type == interfaceType)
return true;
bool implemented = type.GetInterfaces().Contains(interfaceType);
return implemented;
}
That way, if you wanted to check multiple interfaces you could easily modify ImplementsInterface
to take multiple interfaces.
To check if some type implements IEnumerable regardless of T one needs to check the GenericTypeDefinition.
public static bool IsIEnumerableOfT(this Type type)
{
return type.GetInterfaces().Any(x => x.IsGenericType
&& x.GetGenericTypeDefinition() == typeof(IEnumerable<>));
}
The following line
return (type is IEnumerable);
is asking "if an instance of Type
, type
is IEnumerable
", which clearly it is not.
You want to do is:
return typeof(IEnumerable).IsAssignableFrom(type);