Skip to content

Instantly share code, notes, and snippets.

@cammerman
Created November 6, 2012 19:21
Show Gist options
  • Save cammerman/4026865 to your computer and use it in GitHub Desktop.
Save cammerman/4026865 to your computer and use it in GitHub Desktop.
Type extensions to help check for generic closure.
public static class TypeExtensions
{
public static bool Closes(this Type type, Type checkType)
{
if (!checkType.IsGenericTypeDefinition)
throw new ArgumentException("Type being checked against is not an open generic type.");
return
type.IsGenericType
&& type.GetGenericTypeDefinition() == checkType;
}
public static IEnumerable<Type> InheritanceChain(this Type type)
{
yield return type;
var currentType = type.BaseType;
while (currentType != null)
{
yield return currentType;
currentType = currentType.BaseType;
}
}
public static bool Implements<T>(this Type type)
{
return type.Implements(typeof(T));
}
public static bool Implements(this Type type, Type check)
{
if (check.IsGenericTypeDefinition)
return
type.Closes(check)
|| type.InheritanceChain().Any(@class => @class.Closes(check))
|| type.GetInterfaces().Any(@interface => @interface.Closes(check));
return check.IsAssignableFrom(type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment