Search code examples
c#inheritancereflectiontypesdescendant

Get all last descendants of a base type?


This question is an opposite of How to find types that are direct descendants of a base class?

If this is the inheritance hierarchy I have,

class Base
{

}



class Derived1 : Base
{

}

class Derived1A : Derived1
{

}

class Derived1B : Derived1
{

}



class Derived2 : Base
{

}

I need a mechanism to find all the sub types of Base class in a particular assembly which are at the end of the inheritance tree. In other words,

SubTypesOf(typeof(Base)) 

should give me

-> { Derived1A, Derived1B, Derived2 }

Solution

  • This is what I have come up with. Not sure if some more elegant/efficient solutions exist..

    public static IEnumerable<Type> GetLastDescendants(this Type t)
    {
        if (!t.IsClass)
            throw new Exception(t + " is not a class");
    
        var subTypes = t.Assembly.GetTypes().Where(x => x.IsSubclassOf(t)).ToArray();
        return subTypes.Where(x => subTypes.All(y => y.BaseType != x));
    }
    

    And for sake of completeness, I will repost the answer for direct descendants given here

    public static IEnumerable<Type> GetDirectDescendants(this Type t)
    {
        if (!t.IsClass)
            throw new Exception(t + " is not a class");
    
        return t.Assembly.GetTypes().Where(x => x.BaseType == t);
    }