Skip to content

Instantly share code, notes, and snippets.

@AldeRoberge
Created August 25, 2023 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AldeRoberge/691875da494a23ca58c44d3310b4437d to your computer and use it in GitHub Desktop.
Save AldeRoberge/691875da494a23ca58c44d3310b4437d to your computer and use it in GitHub Desktop.
C# ReflectionUtils to get InheritsOrImplements certain class
public static class ReflectionUtils
{
public static bool InheritsOrImplements(this Type child, Type parent)
{
parent = ResolveGenericTypeDefinition(parent);
var currentChild = child.IsGenericType
? child.GetGenericTypeDefinition()
: child;
while (currentChild != typeof(object))
{
if (parent == currentChild || HasAnyInterfaces(parent, currentChild))
return true;
currentChild = currentChild.BaseType != null
&& currentChild.BaseType.IsGenericType
? currentChild.BaseType.GetGenericTypeDefinition()
: currentChild.BaseType;
if (currentChild == null)
return false;
}
return false;
}
private static bool HasAnyInterfaces(Type parent, Type child)
{
return child.GetInterfaces()
.Any(childInterface =>
{
var currentInterface = childInterface.IsGenericType
? childInterface.GetGenericTypeDefinition()
: childInterface;
return currentInterface == parent;
});
}
private static Type ResolveGenericTypeDefinition(Type parent)
{
bool shouldUseGenericType = !(parent.IsGenericType && parent.GetGenericTypeDefinition() != parent);
if (parent.IsGenericType && shouldUseGenericType)
parent = parent.GetGenericTypeDefinition();
return parent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment