Michael Gattuso
Michael Gattuso

Reputation: 13200

List all concrete or abstract classes of object

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

Upvotes: 4

Views: 809

Answers (2)

jason
jason

Reputation: 241641

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.

Upvotes: 10

Chris Pitman
Chris Pitman

Reputation: 13104

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)

Upvotes: 0

Related Questions