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.

0

2 Answers 2

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))
5
  • 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. Sep 23, 2015 at 0:59
  • 1
    Alex, how would you go about searching the inheritance chain of a generic type to accomplish this? Nov 12, 2015 at 11:07
  • 1
    @AlexHopeO'Connor's note is important and I think solution is there stackoverflow.com/questions/457676/… May 25, 2016 at 11:49
  • 2
    For PCL typeof(SomeType).GetTypeInfo().IsAssignableFrom(typeof(Derived).GetTypeInfo())
    – Seafish
    May 15, 2017 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, 2021 at 0:51
23

Try this

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.