HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

Getting all types that implement an interface

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
gettinginterfacetypesthatallimplement

Problem

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

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#26733, score: 963

Revisions (0)

No revisions yet.