188

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

390

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))
Sign up to request clarification or add additional context in comments.

5 Comments

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, how would you go about searching the inheritance chain of a generic type to accomplish this?
@AlexHopeO'Connor's note is important and I think solution is there stackoverflow.com/questions/457676/…
For PCL typeof(SomeType).GetTypeInfo().IsAssignableFrom(typeof(Derived).GetTypeInfo())
For those a little confused about the order, such as myself: typeof(InvalidOperationException).IsAssignableFrom(typeof(Exception)) = false typeof(Exception).IsAssignableFrom(typeof(InvalidOperationException)) = true
25

Try this

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.