Thanks to @drzaus for his good answer , but it can be compressed in oneliner (plus check for null and IEnumerable ):
public static Type GetEnumeratedType(this Type type) => type?.GetElementType() ?? typeof(IEnumerable).IsAssignableFrom(type) ? type.GenericTypeArguments.FirstOrDefault() : null;
Added null checkers to avoid an exception, maybe I shouldn't (feel free to remove the Null Conditional Operators ). A filter has also been added, so the function only works with collections, not universal types.
And keep in mind that this can also be tricked by implemented subclasses that change the collection item, and the developer decided to move the generic-type argument of the collection to a later position.
Shimmy May 7 '17 at 12:02 a.m. 2017-05-07 00:02
source share