Dane O'Connor
Dane O'Connor

Reputation: 77318

Search an assembly for all child types?

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.

Upvotes: 3

Views: 2186

Answers (3)

MartinH
MartinH

Reputation: 21

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
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501143

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);
        }
    }
}

Upvotes: 11

Cristian Libardo
Cristian Libardo

Reputation: 9258

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

Upvotes: 1

Related Questions