How to check if a class inherits another class without instantiating it?

128,789

Solution 1

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))

Solution 2

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

Share:
128,789

Related videos on Youtube

atoMerz
Author by

atoMerz

Stackoverflow CV Linkedin profile

Updated on June 23, 2020

Comments

  • atoMerz
    atoMerz about 4 years

    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.

  • Alex Hope O'Connor
    Alex Hope O'Connor almost 9 years
    Just as a note to anyone else wondering, this won't return true when checking against generic type/interface definitions, as far as I can tell you need to search the inheritance chain and check for generic type definitions yourself.
  • Douglas Gaskell
    Douglas Gaskell over 8 years
    Alex, how would you go about searching the inheritance chain of a generic type to accomplish this?
  • Furkan Ekinci
    Furkan Ekinci about 8 years
    @AlexHopeO'Connor's note is important and I think solution is there stackoverflow.com/questions/457676/…
  • Seafish
    Seafish about 7 years
    For PCL typeof(SomeType).GetTypeInfo().IsAssignableFrom(typeof(Deriv‌​ed).GetTypeInfo())
  • Joel
    Joel over 3 years
    For those a little confused about the order, such as myself: typeof(InvalidOperationException).IsAssignableFrom(typeof(Ex‌​ception)) = false typeof(Exception).IsAssignableFrom(typeof(InvalidOperationEx‌​ception)) = true