Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
I appreciate this is a very old question but I thought I would add another answer for future users as all the answers to date use some form of
Assembly.GetTypes
.Whilst GetTypes() will indeed return all types, it does not necessarily mean you could activate them and could thus potentially throw a
ReflectionTypeLoadException
.A classic example for not being able to activate a type would be when the type returned is
derived
frombase
butbase
is defined in a different assembly from that ofderived
, an assembly that the calling assembly does not reference.So say we have:
If in
ClassC
which is inAssemblyC
we then do something as per accepted answer:Then it will throw a
ReflectionTypeLoadException
.This is because without a reference to
AssemblyA
inAssemblyC
you would not be able to:In other words
ClassB
is not loadable which is something that the call to GetTypes checks and throws on.So to safely qualify the result set for loadable types then as per this Phil Haacked article Get All Types in an Assembly and Jon Skeet code you would instead do something like:
And then:
This worked for me (if you wish you could exclude system types in the lookup):