How to inspect a type inheritance tree properly

You might think this is a trivial thing, with Type.BaseType and Type.GetInterfaces already there. But there's catch: the GetInterfaces method will give you all the implemented interfaces by the concrete type, as well as all its base types, as well as all the interfaces inherited by other interfaces it implements. What a mess! To make it more clear, say you have the following types:

    public interface IBase
    public class Base : IBase, ICloneable
    public class Derived : Base

If you do

    typeof(Derived).GetInterfaces().ToList().ForEach(t => Console.WriteLine(t.FullName));

Here's what you get:

    Test.IBase
    System.ICloneable

If you look back to Derived definition, it doesn't implement any interfaces itself, but rather it's the base class. So, in order to have a more precise information about the type, we should be able to get this instead:

Derived
    Base
        Object
        IBase
        ICloneable

Now, this could be very useful in a few scenarios. My particular one involves finding an adapter that is registered for the closest type to the actual instance (i.e. if I have adapters registered for Derived, IBase and ICloneable, I want to be able to give them priority automatically based on where they appear in the precise type hierarchy)....

Read full article

No Comments