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

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.


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.


A example using Linq:

var types =
  myAssembly.GetTypes()
            .Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);