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
Other answer were not working with a generic interface.
This one does, just replace typeof(ISomeInterface) by typeof (T).
So with
we get all the assemblies
is used to exclude the interface and abstract ones and
to have them in a list.
Other answers here use
IsAssignableFrom
. You can also useFindInterfaces
from theSystem
namespace, as described here.Here's an example that checks all assemblies in the currently executing assembly's folder, looking for classes that implement a certain interface (avoiding LINQ for clarity).
You can set up a list of interfaces if you want to match more than one.
You could use some LINQ to get the list:
But really, is that more readable?
Mine would be this in c# 3.0 :)
Basically, the least amount of iterations will always be:
To find all types in an assembly that implement IFoo interface:
Note that Ryan Rinaldi's suggestion was incorrect. It will return 0 types. You cannot write
because type is a System.Type instance, and will never be of type IFoo. Instead, you check to see if IFoo is assignable from the type. That will get your expected results.
Also, Adam Wright's suggestion, which is currently marked as the answer, is incorrect as well, and for the same reason. At runtime, you'll see 0 types come back, because all System.Type instances weren't IFoo implementors.