3

Using reflection (i'm guessing?), is it possible to create a method that will return a collection of all objects that inherit from an interface named IBlahblah?

public interface IBlahblah;
mrblah
  • 93,893
  • 138
  • 301
  • 415

4 Answers4

11

Assuming you have an assembly (or a list of assemblies) to look in, you can get a collection of types which implement an interface:

var blahs = assembly.GetTypes()
                    .Where(t => typeof(IBlahblah).IsAssignableFrom(t));

You can't get a collection of "live objects" implementing the interface though - at least not without using the debugging/profiling API or something similar.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
4

Do you mean something like this ?

Community
  • 1
  • 1
Shankar R10N
  • 4,736
  • 1
  • 20
  • 24
2

Yes, this is possible, this other stack overflow post gives the solution with LINQ.

Community
  • 1
  • 1
Mitchel Sellers
  • 60,456
  • 13
  • 107
  • 172
2

Yes this is possible :

    var result = new List<Type>();
    foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies())
        foreach(var type in assembly.GetTypes())
            if (typeof(IBlahblah).IsAssignableFrom(type))
                result.Add(type);

And this includes the types outside of the current assembly.

Manitra Andriamitondra
  • 1,221
  • 1
  • 15
  • 21