Wednesday, March 16, 2011

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.

From stackoverflow
  • 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);
            }
        }
    }
    
    TheDeeno : Jon Skeet is everywhere! haha, thanks.
    Aaron Wagner : 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!
  • var a = Assembly.Load("My.Assembly");
    foreach (var t in a.GetTypes().Where(t => t is IMyInterface))
    {
        // there you have it
    }
    
    Jon Skeet : 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.
  • 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
    }
    

0 comments:

Post a Comment