How to check if a class inherits another class without instantiating it? [duplicate]
Suppose I have a class that looks like this:
class Derived : // some inheritance stuff here
{
}
I want to check something like this in my code:
Derived is SomeType;
But looks like is
operator need Derived to be variable of type Dervied, not Derived itself.
I don't want to create an object of type Derived.
How can I make sure Derived inherits SomeType
without instantiating it?
P.S. If it helps, I want something like what where
keyword does with generics.
EDIT:
Similar to this answer, but it's checking an object. I want to check the class itself.
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not