views:

107

answers:

3

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.

+4  A: 
var types = Assembly
    .GetExecutingAssembly()
    .GetTypes()
    .Where(t => typeof(SomeBaseType).IsAssignableFrom(t) && 
                t != typeof(SomeBaseType))
    .ToArray();
Darin Dimitrov
+7  A: 
from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsSubclassOf(typeof(A)) select t;
Sergej Andrejev
+2  A: 

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
Hath