How to find all subclasses of a given class

The following function will return a list of all subclasses inherited from a given class. Please note, that it works only within a single assembly, same as which holds the given superclass.

1
2
3
4
5
6
7
8
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
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

Next function will return all classes implementing a given interface:

1
2
3
4
5
6
7
8
Function FindClassesImplementedInterface(Of TInterface)() As IEnumerable(Of Type)
    Dim baseInterface = GetType(TInterface)
    Dim assembly = baseInterface.Assembly
 
    Return From t In assembly.GetTypes()
        Where t.IsAssignableFrom(baseInterface)
        Select t
End Function
Function FindClassesImplementedInterface(Of TInterface)() As IEnumerable(Of Type)
    Dim baseInterface = GetType(TInterface)
    Dim assembly = baseInterface.Assembly

    Return From t In assembly.GetTypes()
        Where t.IsAssignableFrom(baseInterface)
        Select t
End Function

Happy coding!

Leave a comment

Your email address will not be published. Required fields are marked *