O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required