Skip to content

Instantly share code, notes, and snippets.

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 manisero/5a8dc338d35b565322a1 to your computer and use it in GitHub Desktop.
Save manisero/5a8dc338d35b565322a1 to your computer and use it in GitHub Desktop.
public static Type GetGenericTypeDefinitionImplementation(this Type type, Type definition)
{
if (definition.IsInterface)
{
return type.GetGenericInterfaceDefinitionImplementation(definition);
}
else
{
return type.GetGenericClassDefinitionImplementation(definition);
}
}
public static Type GetGenericInterfaceDefinitionImplementation(this Type type, Type interfaceDefinition)
{
if (type.IsInterface && type.ImplementsGenericDefinition(interfaceDefinition))
{
return type;
}
var interfaces = type.GetInterfaces();
foreach (var @interface in interfaces)
{
if (@interface.ImplementsGenericDefinition(interfaceDefinition))
{
return @interface;
}
}
return null;
}
public static Type GetGenericClassDefinitionImplementation(this Type type, Type classDefinition)
{
if (type == typeof(object))
{
return null;
}
if (type.ImplementsGenericDefinition(classDefinition))
{
return type;
}
return type.BaseType.GetGenericClassDefinitionImplementation(classDefinition);
}
public static bool ImplementsGenericDefinition(this Type type, Type definition)
{
return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == definition;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment