Discovering derived types using reflection

Using reflection, is it possible to discover all types that derive from a given type?

Presumably the scope would be limited to within a single assembly.


Solution 1:

pretty much the same as Darin's but here you go..

    public static List<Type> FindAllDerivedTypes<T>()
    {
        return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));
    }

    public static List<Type> FindAllDerivedTypes<T>(Assembly assembly)
    {
        var derivedType = typeof(T);
        return assembly
            .GetTypes()
            .Where(t =>
                t != derivedType &&
                derivedType.IsAssignableFrom(t)
                ).ToList();

    } 

used like:

var output = FindAllDerivedTypes<System.IO.Stream>();
            foreach (var type in output)
            {
                Console.WriteLine(type.Name);
            }

outputs:

NullStream
SyncStream
__ConsoleStream
BufferedStream
FileStream
MemoryStream
UnmanagedMemoryStream
PinnedBufferMemoryStream
UnmanagedMemoryStreamWrapper
IsolatedStorageFileStream
CryptoStream
TailStream

Solution 2:

var derivedTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                   where t.IsSubclassOf(typeof(A))
                   select t;

Solution 3:

var types = Assembly
    .GetExecutingAssembly()
    .GetTypes()
    .Where(t => typeof(SomeBaseType).IsAssignableFrom(t) && 
                t != typeof(SomeBaseType))
    .ToArray();