Skip to content

Instantly share code, notes, and snippets.

@niikoo
Created January 7, 2019 10:34
Show Gist options
  • Save niikoo/624ece1e53f3effc09a8a635061e3cc3 to your computer and use it in GitHub Desktop.
Save niikoo/624ece1e53f3effc09a8a635061e3cc3 to your computer and use it in GitHub Desktop.
namespace Extensions {
public static class GenericExtensions
{
/// <summary>
/// Check if class inherits a raw generic type, i.e. IEnumerable&lt;&gt;
/// </summary>
/// <param name="generic"></param>
/// <param name="toCheck"></param>
/// <returns></returns>
public static bool IsSubClassOfRawGeneric(this Type toCheck, Type generic, bool checkInterfaces = true)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
return true;
if (checkInterfaces && toCheck.GetInterfaces().Any(iface => iface.Name == generic.Name))
return true;
toCheck = toCheck.BaseType;
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment