13.6. Displaying the Inheritance Hierarchy for a Type

Problem

You need to determine all of the base types that make up a specific class or struct. 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 DisplayInheritanceChain 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 Display InheritanceChain (string asmPath)
	{
	    Assembly asm = Assembly.LoadFrom(asmPath);
	    var typeInfos = from Type type in asm.GetTypes()
	               select new
	               {
	                   FullName = type.FullName,
	                   BaseTypeDisplay = type.GetBaseTypeDisplay()
	               };

	    foreach(var typeInfo in typeInfos)
	    {
	        // Recurse over all base types
	        Console.WriteLine ("Derived Type: " + typeInfo.FullName);
	        Console.WriteLine("Base Type List: " + typeInfo.BaseTypeDisplay);
	        Console.WriteLine();
	    }
	}

DisplayInheritanceChain takes the path to the assembly and retrieves all of the Types in the assembly using GetTypes as part of a query. It then projects the FullName of the Type and the BaseTypeDisplay for the type. The BaseTypeDisplay is a string holding all of the base types and is generated by the extension method GetBaseTypeDisplay. GetBaseTypeDisplay gets the name of each base type using the GetBaseTypes extension method and reverses the order of the types with a call to Reverse. The call to Reverse is done as the types are most derived to ...

Get C# 3.0 Cookbook, 3rd Edition 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.