Thanks to @drzaus for his nice answer, but it can be compressed to a oneliner (plus check for null
s and IEnumerable
type):
public static Type GetEnumeratedType(this Type type) =>
type?.GetElementType()
?? typeof(IEnumerable).IsAssignableFrom(type)
? type.GenericTypeArguments.FirstOrDefault()
: null;
Added null
checkers to avoid exception, maybe I shouldn't (feel free to remove the Null Conditional Operators).
Also added a filter so the function only works on collections, not any generic types.
And bear in mind that this could also be fooled by implemented subclasses that change the subject of the collection and the implementor decided to move the collection's generic-type-argument to a later position.
Converted answer for C#8 and nullability:
public static Type GetEnumeratedType(this Type type) =>
((type?.GetElementType() ?? (typeof(IEnumerable).IsAssignableFrom(type)
? type.GenericTypeArguments.FirstOrDefault()
: null))!;