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.
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.
var types = Assembly
.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(SomeBaseType).IsAssignableFrom(t) &&
t != typeof(SomeBaseType))
.ToArray();
from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsSubclassOf(typeof(A)) select t;
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