views:

541

answers:

4

This is likely going to be an easy answer and I'm just missing something, but here goes...If I have a Type, (that is, an actual System.Type...not an instance) how do I tell if it inherits from another specific base type?

+11  A: 

EDIT: Note that the above solution will fail if the base type you are looking for is an interface. The following solution will work for any type of inheritance, be it class or interface.

// Returns true if "type" inherits from "baseType"
public static bool Inherits(Type type, Type baseType) {
    return baseType.IsAssignableFrom(type)
}

(Semi)Helpful extract from the MSDN article:

true if [the argument] and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of [the argument], or if the current Type is an interface that [the argument] implements, or if [the argument] is a generic type parameter and the current Type represents one of the constraints of [the argument]. false if none of these conditions are true, or if [the argument] is a null reference (Nothing in Visual Basic).

Chris Marasti-Georg
Yep, unlike Type.IsSubclassOf, this also works on interfaces.
petr k.
+6  A: 

Use the IsSubclassOf method of the System.Type class.

chakrit
Will this work across interfaces as well?
Chris Marasti-Georg
For interfaces, there's GetInterface method
chakrit
So... this doesn't completely answer the question. It would not work if type a implements interface b
Chris Marasti-Georg
For including interfaces, you're better off with IsAssignableFrom()
Mark Cidade
the author was asking for "inherits from a specific base class", no?
chakrit
No, he did not say "class". He said "type"
Chris Marasti-Georg
A: 

My bad, i missed the point, i wrote the wrong thimg here

mattlant
He does not have objects, just their types
Chris Marasti-Georg
i wish i could delete :) I was reading to fast when i replied :/ feel free to click the down button :)
mattlant
You do not have a link next to "edit" beneath your text to delete?
Chris Marasti-Georg
+2  A: 

One thing to clarify between Type.IsSubTypeOf() and Type.IsAssignableFrom():

IsSubType() will return true only if the given type is derived from the specified type. It will return false if the given type IS the specified type.

IsAssignableFrom() will return true if the given type is either the specified type or derived from the specified type.

So if you are using these to compare BaseClass and DerivedClass (which inherits from BaseClass) then:

BaseClassInstance.GetType.IsSubTypeOf(GetType(BaseClass)) = FALSE BaseClassInstance.GetType.IsAssignableFrom(GetType(BaseClass)) = TRUE

DerivedClassInstance.GetType.IsSubTypeOf(GetType(BaseClass)) = TRUE DerivedClassInstance.GetType.IsAssignableFrom(GetType(BaseClass)) = TRUE

STW