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.
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.
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);
}
}
}
var a = Assembly.Load("My.Assembly");
foreach (var t in a.GetTypes().Where(t => t is IMyInterface))
{
// there you have it
}
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
}