12.7. Displaying the Inheritance Hierarchy for a Type

Problem

You need to determine all of the base types that make up a specific type. Essentially, you need to determine the inheritance hierarchy of a type starting with the base (least derived) type and ending with the specified (most derived) type.

Solution

Use the DisplayTypeHierarchy method to display the entire inheritance hierarchy for all types existing in an assembly specified by the asmPath parameter. Its source code is:

public static void DisplayTypeHierarchy (string asmPath)
{
    Assembly asm = Assembly.LoadFrom(asmPath);
    foreach(Type asmType in asm.GetTypes( ))
    {
        // Recurse over all base types
        Console.WriteLine ("Derived Type: " + asmType.FullName);
        Console.WriteLine ("Base Type List: " + GetBaseTypeList(asmType));
        Console.WriteLine ( );
    }
}

DisplayTypeHierarchy in turn calls GetBaseTypeList, a private method that uses recursion to get all base types. Its source code is:

private static string GetBaseTypeList(Type type)
{
    if (type != null)
    {
        string baseTypeName = GetBaseType(type.BaseType);
        if (baseTypeName.Length <= 0)
        {
            return (type.Name);
        }
        else
        {
            return (baseTypeName + "::" + type.Name);
        }
    }
    else
    {
        return ("");
    }
}

If you want to obtain only the inheritance hierarchy of a specific type as a string, use the following DisplayTypeHierarchy overload:

public static void DisplayTypeHierarchy(string asmPath,string baseType) { Assembly asm = Assembly.LoadFrom(asmPath); string typeHierarchy = GetBaseTypeList(asm.GetType(baseType)); ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.