views:

321

answers:

3

To check if a type is a subclass of another type in C#, it's easy:

typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true

However, this will fail:

typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false

Is there any way to check whether a type is either a subclass OR of the base class itself, without using an OR operator or using an extension method?

+3  A: 
typeof(BaseClass).IsAssignableFrom(unknownType);
Marc Gravell
+1  A: 

You should try using Type.IsAssignableFrom instead.

Thomas
+8  A: 

Use this:

if (typeof(BaseClass).IsAssignableFrom(typeof(SubClass)))

Note that you reverse the order of the classes compared to the code you have in your question.

Link: Type.IsAssignableFrom Method.

Lasse V. Karlsen
Thanks! I'll mark this as the correct answer (gotta wait 8 more minutes) since you mentioned that the check has to be reversed and provided a link to the MSDN documentation.
Daniel T.
Note that this doesn't actually do what the question asked for; this does not determine whether one type is a subclass of another, but rather whether one type is assignment compatible with another. An array of uint isn't a subclass of an array of int, but they are assignment compatible. IEnumerable<Giraffe> isn't a subclass of IEnumerable<Animal>, but they are assignment compatible in v4.
Eric Lippert
Thanks Eric, good to keep in mind.
Daniel T.
Shoot, I didn't think of that, thanks Eric!
Lasse V. Karlsen