I have a situation where I need to see if two viewmodels derive from the same base.
Model:
class BaseModel;
class DerivedModel1 : BaseModel;
class DerivedModel2 : BaseModel;
class DerivedModel3 : DerivedModel2;
Given this model, I want to know when DerivedModel1 and DerivedModel3 are both from the same BaseModel. It is not guaranteed that these classes are in the same assembly and there may be a deeper hierarchy as well. It is also not guaranteed that I know what BaseModel is.
I’ve tried DerivedModel1.GetType().IsAssignableFrom(DerivedModel3.GetType()); but as you already know this won’t work because of the depth of the hierarchy.
Any thoughts?
You can check it like this:
IsAssignableFromwill work, too, if you provide the common base, the hierarchy depth has nothing to do here.If the
TBaseis unknown, you can climb up inheritance trees of both classes, as InBetween suggested. And then compare both trees to check if they share any common type other thanobject. It can look somehow like that: