Question

Is it possible in C#, via reflection or some other method, to return a list all superclasses (concrete and abstract, mostly interested in concrete classes) of an object. For example passing in a "Tiger" class would return:

  1. Tiger
  2. Cat
  3. Animal
  4. Object
Was it helpful?

Solution

static void VisitTypeHierarchy(Type type, Action<Type> action) {
    if (type == null) return;
    action(type);
    VisitTypeHierarchy(type.BaseType, action);
}

Example:

VisitTypeHierarchy(typeof(MyType), t => Console.WriteLine(t.Name));

You can easily deal with abstract classes by using the Type.IsAbstract property.

OTHER TIPS

Sure, use the "GetType()" method to get the type of the provided object. Each Type instance has a "BaseType" property which provides the directly inherited type. You can just recursively follow the types until you find a Type with a null BaseType (ie Object)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top