I\'m doing a heavy bit of reflection in my current project, and I\'m trying to provide a few helper methods just to keep everything tidy.
I\'d like to provide a pair
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<>));
}
In addition to Type.IsAssignableFrom(Type), you can also use Type.GetInterfaces():
public static bool ImplementsInterface(this Type type, Type interface)
{
bool implemented = type.GetInterfaces().Contains(interface);
return implemented;
}
That way, if you wanted to check multiple interfaces you could easily modify ImplementsInterface to take multiple interfaces.
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);