This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET 1.1+

Reflecting Type Hierarchy Information

The twelfth part of the Reflection tutorial describes how reflection can be used to investigate the types within inheritance hierarchies. It explains how to find the base type of a class and how to determine whether one class is a subclass of another.

Inheritance and Reflection

In the previous article in this tutorial we looked at how to obtain details of the interfaces implemented by a class or structure using reflection. It will come as no surprise that you can also use reflection to obtain the details of classes in an inheritance relationship. Specifically, you can examine a Type instance to request its base class or perform a test to determine if one class is a subclass of another.

We'll demonstrate these two operations using three classes. The "Animal" class is our base class with a subclass of "Dog". A more specialised version of Dog, named "Labrador" completes a three tier hierarchy. As we will only be working with types, the test classes have no members defined. This keeps the code as simple as possible.

public class Animal

public class Dog : Animal

public class Labrador : Dog

Reflecting Base Types

Unlike when reflecting the interfaces that a class or structure implements, there can only be a maximum of one base type for a class. We can obtain a Type object that represents this base type by reading the BaseType property of an existing Type instance. For example, the code below obtains the superclass of Dog and outputs its name.

Type type = typeof(Dog);
Console.WriteLine(type.BaseType.Name);  // Animal

The only time that there is a problem with the BaseType property is when you attempt to get the base type for a class that doesn't have one. As the sample code below shows, when you try to read the base type of the System.Object class, a NullReferenceException is thrown.

Type type = typeof(object);
Console.WriteLine(type.BaseType.Name);  // NullReferenceException

Checking if One Class is a Subclass of Another

You can check if one class is a subclass of another using the Type class' IsSubclassOf method. The method has a single parameter that accepts the type to be tested. If the passed class is a supertype of the Type being operated upon, the method returns true. If not, it returns false.

bool isSubclass;
isSubclass = typeof(Dog).IsSubclassOf(typeof(Animal));       // true
isSubclass = typeof(Labrador).IsSubclassOf(typeof(Animal));  // true
isSubclass = typeof(Dog).IsSubclassOf(typeof(Labrador));     // false
19 May 2012