Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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)); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata