Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Created February 4, 2021 10:35
Show Gist options
  • Save NDiiong/2d4104dff59b14f1e929e122e4202fc2 to your computer and use it in GitHub Desktop.
Save NDiiong/2d4104dff59b14f1e929e122e4202fc2 to your computer and use it in GitHub Desktop.
GetAnyElementType
public static class TypeExtension
{
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static Type GetAnyElementType(this Type type)
{
// Type is Array
// short-circuit if you expect lots of arrays
if (type.IsArray)
return type.GetElementType();
// type is IEnumerable<T>;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return type.GetGenericArguments()[0];
// type implements/extends IEnumerable<T>;
var enumType = type.GetInterfaces()
.Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(t => t.GenericTypeArguments[0])
.FirstOrDefault();
return enumType ?? type;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment