Code/Reflection/TypeExtensions.cs
using System;
namespace ExtendedBox.Reflection;
public static class TypeExtensions
{
public static bool IsAssignableToGenericType(this Type givenType, Type genericType)
{
if(TypeLibrary.GetType(genericType) is null)
throw new InvalidOperationException($"Using TypeLibrary with type {genericType.FullName} is blocked by whitelist.");
var interfaceTypes = givenType.GetInterfaces();
foreach(var interfaceType in interfaceTypes)
{
if(interfaceType.IsGenericType)
{
var genericTypeDefinition = TypeLibrary.GetType(interfaceType)?.TargetType;
if(genericTypeDefinition is not null && genericTypeDefinition == genericType)
return true;
}
}
if(givenType.IsGenericType)
{
var genericTypeDefinition = TypeLibrary.GetType(givenType)?.TargetType;
if(genericTypeDefinition is not null && genericTypeDefinition == genericType)
return true;
}
Type? baseType = givenType.BaseType;
if(baseType == null)
return false;
return baseType.IsAssignableToGenericType(genericType);
}
}