Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 587
Michael Gattuso Avatar asked Dec 30 '22 09:12

Michael Gattuso


1 Answers

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.

like image 79
jason Avatar answered Jan 08 '23 03:01

jason