Title: Find class ancestors in C#
The example Find classes that implement an interface or that are descendants of a given class in C# shows how to find a list of classes that are descendants of a class or interface. This example uses similar code to list classes. Then if you click on a class in the list on the left, the program uses the following code to display the class ancestors for selected class in the list on the right.
// Display the ancestors of the selected class.
private void lstClasses_SelectedIndexChanged(object sender, EventArgs e)
if (lstClasses.SelectedIndex == -1) return;
Cursor = Cursors.WaitCursor;
// Get the type.
List<TypeInfo> types = new List<TypeInfo>();
TypeInfo the_type = (TypeInfo)lstClasses.SelectedItem;
for (Type parent = the_type.TheType.BaseType;
parent != null;
parent = parent.BaseType)
types.Insert(0, new TypeInfo(parent));
for (int i = 0; i < types.Count; i++)
new string(' ', i * 2) + types[i].TheType.Name);
Cursor = Cursors.Default;
The code clears the result ListBox. It then creates a List of TypeInfo objects called types to hold the selected class's ancestry. The TypeInfo class, which holds Type objects and their names, is described shortly.
The code gets the TypeInfo object that was clicked in the left ListBox and adds it to the types list.
The code then enters a loop. It sets the variable parent equal to the parent of the selected type. As long as the parent variable is not null, the program inserts a new TypeInfo object representing the parent at the beginning of the types list and moves the variable parent to that object's parent class.
When parent has climbed to the top of the inheritance hierarchy, the loop ends. At that point the program uses another loop to add the TypeInfo objects in the types list to the ListBox on the right, indenting each by 2 spaces more than the previous item to emphasize the fact that each item is derived from the one above.
The following code shows the TypeInfo class, which is used to store information about the types shown in the ListBox controls.
public Type TheType;
public TypeInfo(Type the_type)
TheType = the_type;
public override string ToString()
This class simply holds a Type object and overrides its ToString method to return that object's name. The ListBox control uses an object's ToString method to display the object. This program adds TypeInfo objects to the ListBox controls so they display the Type names.
Download the example to experiment with it and to see additional details.