tags:

views:

175

answers:

3

I'd like to find all the types inheriting from a base/interface. Anyone have a good method to do this? Ideas?

I know this is a strange request but its something I'm playing with none-the-less.

+10  A: 

Use Assembly.GetTypes() to get all the types, and Type.IsAssignableFrom() to check for inheritance. Let me know if you need code - and also whether or not you're using .NET 3.5. (A lot of reflection tasks like this are simpler with LINQ to Objects.)

EDIT: As requested, here's an example - it finds everything in mscorlib which implements IEnumerable. Note that life is somewhat harder when the base type is generic...

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);
        }
    }
}
Jon Skeet
Jon Skeet is everywhere! haha, thanks.
TheDeeno
I'd love to see that code since I can't get Type.IsAssignableFrom() to work the way I'm understanding it. I'm on 3.5 sp1. Thanks!
Aaron Wagner
Thank you Jon Skeet!
Aaron Wagner
+1  A: 
var a = Assembly.Load("My.Assembly");
foreach (var t in a.GetTypes().Where(t => t is IMyInterface))
{
    // there you have it
}
Cristian Libardo
No, that won't work - "is" checks whether an *object* implements an interface, and the instance of "Type" doesn't implement IMyInterface. That's why I suggested using Type.IsAssignableFrom.
Jon Skeet
A: 

Or for subclasses of a base class:

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