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<>))
does not work.
@EnocNRoll - Ananda Gopal 's answer is interesting, but in case an instance is not instantiated beforehand or you want to check with a generic type definition, I'd suggest this method:
and use it like:
There are four conditional cases when both
t
(to be tested) andd
are generic types and two cases are covered byt==d
which are (1)neithert
nord
is a generic definition or (2) both of them are generic definitions. The rest cases are one of them is a generic definition, only whend
is already a generic definition we have the chance to say at
is ad
but not vice versa.It should work with arbitrary classes or interfaces you want to test, and returns what as if you test an instance of that type with the
is
operator.You can try this extension
This can all be done easily with linq. This will find any types that are a subclass of generic base class GenericBaseType.
Here's a little method I created for checking that a object is derived from a specific type. Works great for me!