Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all types that implement an interface

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 
like image 623
juan Avatar asked Aug 25 '08 19:08

juan


People also ask

Which types can implement an interface?

An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

Do I have to implement all interface methods?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.

Can an interface be implemented by multiple classes?

Yes an interface can be implemented by multiple classes.


1 Answers

Mine would be this in c# 3.0 :)

var type = typeof(IMyInterface); var types = AppDomain.CurrentDomain.GetAssemblies()     .SelectMany(s => s.GetTypes())     .Where(p => type.IsAssignableFrom(p)); 

Basically, the least amount of iterations will always be:

loop assemblies    loop types     see if implemented. 
like image 67
Darren Kopp Avatar answered Oct 10 '22 15:10

Darren Kopp