Looking for an assembly for all child types?

I would like to find all types inheriting the base / interface. Anyone have a good way to do this? Ideas?

I know this is a strange request, but its what I play with does not make any difference.

+3
source share
3 answers

Use Assembly.GetTypes () to get all types, and Type.IsAssignableFrom () to check inheritance. Let me know if you need code, or if you are using .NET 3.5. (Many reflection tasks like this are easier with LINQ to Objects.)

EDIT: as requested, here's an example - it finds everything in mscorlibthat it implements IEnumerable. Note that life is a little more complicated when the base type is shared ...

using System;
using System.Collections;
using System.Linq;
using System.Reflection;

class Test
{
    static void Main()
    {
        Assembly assembly = typeof(string).Assembly;
        Type target = typeof(IEnumerable);        
        var types = assembly.GetTypes()
                            .Where(type => target.IsAssignableFrom(type));

        foreach (Type type in types)
        {
            Console.WriteLine(type.Name);
        }
    }
}
+11
var a = Assembly.Load("My.Assembly");
foreach (var t in a.GetTypes().Where(t => t is IMyInterface))
{
    // there you have it
}
+1

:

var a = Assembly.Load("My.Assembly");
foreach (var t in a.GetTypes().Where(t => t.IsSubClassOf(typeof(MyType)))
{
    // there you have it
}
0

All Articles