Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all the classes which implement a given interface?

Tags:

c#

reflection

Under a given namespace, I have a set of classes which implement an interface. Let's call it ISomething. I have another class (let's call it CClass) which knows about ISomething but doesn't know about the classes which implement that interface.

I would like that CClass to look for all the implementation of ISomething, instantiate an instance of it and execute the method.

Does anybody have an idea on how to do that with C# 3.5?

like image 467
Martin Avatar asked Mar 31 '09 02:03

Martin


People also ask

How many classes can a given interface implement?

But if you really really want to know the theoretical maximum number of interfaces a class can implement, it's 65535.

How do you find the class of an interface?

Differences between a Class and an Interface:A class can be instantiated i.e, objects of a class can be created. An Interface cannot be instantiated i.e, objects cannot be created. Classes does not support multiple inheritance. Interface supports multiple inheritance.

How do I find all implemented classes for an interface in eclipse?

Put the cursor on the name of the interface and press F4 (Open Type Hierarchy). That will open a window that shows a tree with all classes that Eclipse can find that implement the interface.


2 Answers

A working code-sample:

var instances = from t in Assembly.GetExecutingAssembly().GetTypes()                 where t.GetInterfaces().Contains(typeof(ISomething))                          && t.GetConstructor(Type.EmptyTypes) != null                 select Activator.CreateInstance(t) as ISomething;  foreach (var instance in instances) {     instance.Foo(); // where Foo is a method of ISomething } 

Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.

like image 169
Matt Hamilton Avatar answered Oct 03 '22 07:10

Matt Hamilton


You can get a list of loaded assemblies by using this:

Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies() 

From there, you can get a list of types in the assembly (assuming public types):

Type[] types = assembly.GetExportedTypes(); 

Then you can ask each type whether it supports that interface by finding that interface on the object:

Type interfaceType = type.GetInterface("ISomething"); 

Not sure if there is a more efficient way of doing this with reflection.

like image 22
Mitch Denny Avatar answered Oct 03 '22 06:10

Mitch Denny