Created
February 4, 2021 10:35
-
-
Save NDiiong/2d4104dff59b14f1e929e122e4202fc2 to your computer and use it in GitHub Desktop.
GetAnyElementType
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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