Home > .Net, C# > How to find all types which derive from given type.

How to find all types which derive from given type.

Suppose you need to find all types in assembly, which derive from given type (using C#.NET). What we need is reflection, to collect all types in a given assembly, using “Assembly.GetTypes” and then to select the required types only.

1) As a first attempt, we will use a function “IsSubclassOf” for every type in assembly:

public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
        var types = Assembly.GetAssembly(type).GetTypes();
        return types.Where(curType => curType.IsSubclassOf(type));
}

This works good. So, why this attempt is not a solution? Because the function “IsSubclassOf” works with classes, but not with interfaces. It returns “false” for interface.

2) Now we will use another function “IsAssignableFrom”. If gets an interface, the function checks, whether the type implements it. If gets a type – checked is being inherited. See the second attempt:

public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
        var types = Assembly.GetAssembly(type).GetTypes();
        return types.Where(curType => type.IsAssignableFrom(curType));
}

The function is much better – it works for both classes and interfaces. Is there a problem? Sure 😉 The input class/interface was accounted, because it is self-assignable.

3) Let’s rewrite the last time, using appropriate condition:

public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
        var types = Assembly.GetAssembly(type).GetTypes();
        return types.Where(type.IsAssignableFrom).Where(curType => curType != type);
}

That’s all. This function finds all types, derived from given type: either class or interface.
Note: the function will not work for value types – they can’t be inhereted 🙂

Categories: .Net, C# Tags: ,
  1. No comments yet.
  1. No trackbacks yet.