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?

+4
source share
4 answers

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; } 
+8
source

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> implements IY<string> . This can be done using reflection or using the as operator.

  • Type.GetInterafces() (or Type.GetInterface(t) ).

The second will be easier. Moreover, this also gives false:

 Type t = typeof(List<string>).GetGenericTypeDefinition(); bool isAssign = typeof(IEnumerable<>).IsAssignableFrom(t); 
+4
source

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<>))); 
+2
source

The following returns true and applies to the point, checking the interfaces:

  enumerable = typeof(List<string>).GetInterfaces() .Contains(typeof(IEnumerable<string>)); 
+1
source

All Articles