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)
You can use the Type.IsAssignableFrom
method.
In VB:
If GetType(Domain).IsAssignableFrom(GetType(DerivedThree)) Then
In C#:
if (typeof(Domain).IsAssignableFrom(typeof(DerivedThree)))
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With