views:

79

answers:

2

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
+8  A: 
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.

Jason
+1 for conciseness!
CesarGon
What a surprisingly simple answer but just what I looking for. Thanks!
Michael Gattuso
A: 

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)

Chris