Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a type is in the inheritance hierarchy

I need to determine if an object has a specific type in it's inheritance hierarchy, however I can't find a good way of doing it.

An very basic example version of my classes are:

Public Class Domain

End Class

Public Class DerivedOne
    Inherits Domain

End Class

Public Class DerivedTwo
    Inherits DerivedOne

End Class

Public Class DerivedThree
    Inherits Domain

End Class

The following does work, however it isn't very elegant in my opinion. Also the more levels of inheritance that get created, the more checks need to be done and it would be easy to forget this piece of code needs to be updated.

If GetType(T) Is GetType(Domain) OrElse _
    GetType(T).BaseType Is GetType(Domain) OrElse _
    GetType(T).BaseType.BaseType Is GetType(Domain) Then

End If

Is there a way of getting 'Is type of Domain anywhere in T's inheritance hierarchy'?

(Answers welcome in C# or VB.NET)


UPDATE

One bit of vital information I missed out due to my own idiocy!

T is a Type object (from the class' generic type)

like image 567
XN16 Avatar asked May 31 '13 14:05

XN16


2 Answers

You can use the Type.IsAssignableFrom method.

In VB:

If GetType(Domain).IsAssignableFrom(GetType(DerivedThree)) Then

In C#:

if (typeof(Domain).IsAssignableFrom(typeof(DerivedThree)))
like image 106
Dan Puzey Avatar answered Nov 13 '22 23:11

Dan Puzey


Why is nobody mentioning Type.IsSubclassOf(Type) ?

https://learn.microsoft.com/en-us/dotnet/api/system.type.issubclassof?view=netframework-4.7.2

Careful, it returns false if called for two equal types ;)

like image 41
floydheld Avatar answered Nov 13 '22 23:11

floydheld