in extensions/Worker.Extensions.Shared/Reflection/TypeExtensions.cs [40:80]
public static bool TryGetCollectionElementType(this Type type, out Type? elementType)
{
elementType = null;
if (!type.IsCollectionType())
{
return false;
}
// Check if the type is an array
if (type.IsArray)
{
elementType = type.GetElementType();
return true;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
elementType = type.GetGenericArguments()[0];
return true;
}
// if generic, get generic type definition, check if that is IEnumerable<>, ICollection<> or IList<>. If so, then pull off the first generic argument.
// Traverse the inheritance hierarchy to find the first generic interface
while (type is not null)
{
var interfaceType = type.GetInterfaces().FirstOrDefault(t => t.IsGenericType
&& (t.GetGenericTypeDefinition() == typeof(IEnumerable<>)
|| t.GetGenericTypeDefinition() == typeof(ICollection<>)
|| t.GetGenericTypeDefinition() == typeof(IList<>)));
if (interfaceType is not null)
{
elementType = interfaceType.GetGenericArguments()[0];
return true;
}
type = type.BaseType!;
}
return false;
}