C# - Discovering derived types using reflection

C# - Discovering derived types using reflection

C# C# Useful extensions

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

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

Source

StackOverflow - Discovering derived types using reflection - https://stackoverflow.com/questions/2362580/discovering-derived-types-using-reflection

Archive

Previous Post Next Post