How to find all types in an assembly that inherit from a particular C # type

How do you get a collection of all types that inherit from a specific other type?

+73
reflection c #
Aug 12 '09 at 20:01
source share
4 answers

Something like:

public IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType) { return assembly.GetTypes().Where(t => baseType.IsAssignableFrom(t)); } 

If you need to handle generics, this becomes a bit more complicated (for example, passed as an open type List<> , but it expects a type returned from List<int> ). Otherwise it's easy though :)

If you want to exclude the type itself, you can do it quite easily:

 public IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType) { return assembly.GetTypes().Where(t => t != baseType && baseType.IsAssignableFrom(t)); } 

Note that this will also allow you to specify an interface and find all types that implement it, rather than just working with classes like Type.IsSubclassOf .

+126
Aug 12 '09 at 20:04
source share
— -

The next method will get a set of types that inherit the type.

FROM#

 public IEnumerable<Type> FindSubClassesOf<TBaseType>() { var baseType = typeof(TBaseType); var assembly = baseType.Assembly; return assembly.GetTypes().Where(t => t.IsSubclassOf(baseType)); } 

Vb.net

 Public Function FindSubClasses(Of TBaseType)() As IEnumerable(Of Type) Dim baseType = GetType(TBaseType) Dim assembly = baseType.Assembly Return From t In assembly.GetTypes() Where t.IsSubClassOf(baseType) Select t End Function 

If you need to include types that implement the interface, see @Jon Skeet's answer.

+19
Dec 25 2018-10-12T00:
source share

You should list all types and check for each if it inherits the one you are looking for.

Some code, such as this question , may be helpful to you.

+1
Aug 12 '09 at 20:06
source share

Consider using this method (written for PCL):

 public IEnumerable<Type> FindDerivedTypes( Assembly assembly, Type baseType ) { TypeInfo baseTypeInfo = baseType.GetTypeInfo(); bool isClass = baseTypeInfo.IsClass, isInterface = baseTypeInfo.IsInterface; return from type in assembly.DefinedTypes where isClass ? type.IsSubclassOf( baseType ) : isInterface ? type.ImplementedInterfaces.Contains( baseTypeInfo.AsType() ) : false select type.AsType(); } 
0
Oct 25 '16 at 11:04 on
source share



All Articles