Created
June 4, 2013 13:50
-
-
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.
This file contains hidden or 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 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