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
  • 99,669
  • 140
  • 310
  • 420

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,421,763
  • 867
  • 9,128
  • 9,194
4

Do you mean something like this ?

Community
  • 1
  • 1
Shankar R10N
  • 4,926
  • 1
  • 21
  • 24
2

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

Community
  • 1
  • 1
Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173
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,249
  • 1
  • 15
  • 21