Skip to content

Instantly share code, notes, and snippets.

@alantsai
Last active May 9, 2016 04:21
Show Gist options
  • Save alantsai/566a7a6d715d87dde08921d38ea92cf7 to your computer and use it in GitHub Desktop.
Save alantsai/566a7a6d715d87dde08921d38ea92cf7 to your computer and use it in GitHub Desktop.
Check up the inheritance chanin if a class inherit a generic type From http://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a-generic-class #csharp

I have a generic class in my project with derived classes.

public class GenericClass<T> : GenericInterface<T>
{
}
public class Test : GenericClass<SomeType>
{
}

Is there any way to find out if a Type object is derived from GenericClass?

t.IsSubclassOf(typeof(GenericClass<>))

public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic) {
while (toCheck != null && toCheck != typeof(object)) {
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur) {
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