Find all classes that inherit a certain class

May 25, 2009 · Follow on Twitter and Mastodon archive

In a typed language, it can be handy to retrieve all types that inherit a certain base class. Let’s have a look at how to do this.

You first need to create an assembly reference, where the calling assembly is the one that is executing your code. You can then retrieve all types in that assembly and filter the collection to find the types that inherit the class of interest.

public static IEnumerable<Type> GetClasses(Type baseType)
{
    var assembly = Assembly.GetCallingAssembly();
    var allTypes = assembly.GetTypes();
    return allTypes.Where(type => type.IsSubclassOf(baseType));
}

Note that this will only return the types in the provided assembly. If you have a distributed system with multiple assemblies, you have to check all of them.

Discussions & More

Please share any ideas, feedback or comments you may have in the Disqus section below, or by replying on Twitter or Mastodon..

If you found this text interesting, make sure to follow me on Twitter and Mastodon for more content like this, and to be notified when new content is published.

If you like & want to support my work, please consider sponsoring me on GitHub Sponsors.