Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gabrieljoelc/5706069 to your computer and use it in GitHub Desktop.
Save gabrieljoelc/5706069 to your computer and use it in GitHub Desktop.
superType#IsAssignableFrom(subType) won't return true when the type on the left side is a generic and the type parameter on the right is its subtype. This extension method does it. I ripped it off of this answer from SO: http://stackoverflow.com/a/1075059/34315.
public static class TypeExtensions
{
public static bool IsGenericTypeAssignableFrom(this Type genericType, Type givenType)
{
var interfaceTypes = givenType.GetInterfaces();
if (interfaceTypes.Any(it => it.IsGenericType && it.GetGenericTypeDefinition() == genericType))
{
return true;
}
if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
return true;
Type baseType = givenType.BaseType;
if (baseType == null) return false;
return genericType.IsGenericTypeAssignableFrom(baseType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment