163

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.

Community
  • 1
  • 1
atoMerz
  • 7,216
  • 15
  • 61
  • 100

2 Answers2

329

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))
Wernight
  • 34,346
  • 23
  • 113
  • 131
Ani
  • 107,182
  • 23
  • 252
  • 300
  • 5
    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. – Alex Hope O'Connor Sep 23 '15 at 00:59
  • 1
    Alex, how would you go about searching the inheritance chain of a generic type to accomplish this? – Douglas Gaskell Nov 12 '15 at 11:07
  • 1
    @AlexHopeO'Connor's note is important and I think solution is there http://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a-generic-class – Furkan Ekinci May 25 '16 at 11:49
  • 2
    For PCL `typeof(SomeType).GetTypeInfo().IsAssignableFrom(typeof(Derived).GetTypeInfo())` – Seafish May 15 '17 at 16:51
  • 3
    For those a little confused about the order, such as myself: `typeof(InvalidOperationException).IsAssignableFrom(typeof(Exception)) = false` `typeof(Exception).IsAssignableFrom(typeof(InvalidOperationException)) = true` – Joel Feb 24 '21 at 00:51
23

Try this

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

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

Haris Hasan
  • 29,296
  • 10
  • 87
  • 121