GetGenericTypeDefinition returns false when searching for IEnumerable <T> in List <T>
Following this question , why is enumerable in this:
Type type = typeof(List<string>); bool enumerable = (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)); return false ?
Change 1
As stated above, it does not work, what would be the best way to determine if the class implements IEnumerable?
Here I can use GetListType(type) and check for null :
static Type GetListType(Type type) { foreach (Type intType in type.GetInterfaces()) { if (intType.IsGenericType && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { return intType.GetGenericArguments()[0]; } } return null; } Because the
(typeof(List<String>)).GetGenericTypeDefinition() returns
typeof(List<>) GetGenericTypeDefinition can return only one type, and not all unrelated types implemented by the target instance of Type .
To determine if X<T> IY<T> implements either
Reify T (i.e. make it a real type) and check with specific types. That is,
X<string>implementsIY<string>. This can be done using reflection or using theasoperator.Type.GetInterafces()(orType.GetInterface(t)).
The second will be easier. Moreover, this also gives false:
Type t = typeof(List<string>).GetGenericTypeDefinition(); bool isAssign = typeof(IEnumerable<>).IsAssignableFrom(t); If you want to quickly check for specific closed generic types - for example, to check if List<string> IEnumerable<string> - implements, you can do something like this:
Type test = typeof(List<string>); bool isEnumerable = typeof(IEnumerable<string>).IsAssignableFrom(test); If you want to use a more universal solution for any IEnumerable<T> , then you will need to use something like this:
Type test = typeof(List<string>); bool isEnumerable = test.GetInterfaces().Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IEnumerable<>)));