I have a generic class in my project with derived classes.
public class GenericClass : GenericInterface
{
}
public class Test : GenericCla
@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:
public static bool TypeIs(this Type x, Type d) {
if(null==d) {
return false;
}
for(var c = x; null!=c; c=c.BaseType) {
var a = c.GetInterfaces();
for(var i = a.Length; i-->=0;) {
var t = i<0 ? c : a[i];
if(t==d||t.IsGenericType&&t.GetGenericTypeDefinition()==d) {
return true;
}
}
}
return false;
}
and use it like:
var b = typeof(char[]).TypeIs(typeof(IList<>)); // true
There are four conditional cases when both t
(to be tested) and d
are generic types and two cases are covered by t==d
which are (1)neither t
nor d
is a generic definition or (2) both of them are generic definitions. The rest cases are one of them is a generic definition, only when d
is already a generic definition we have the chance to say a t
is a d
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.