C# .NET - List classes that implement an interface

Asked By Bieters Bieters on 06-Mar-12 08:25 AM
Hello,

is there an easy way to figure out which classes implement a particular interface?

For example the method 'Database.SetInitializer' of entity framework 5
In MSDN help:
'Declaration
Public Shared Sub SetInitializer(Of TContext As DbContext) ( _
	strategy As IDatabaseInitializer(Of TContext) _
)

Parameters

strategy
Type: http://msdn.microsoft.com/en-us/library/gg696323%28v=vs.103%29.aspx(Of TContext)
The strategy.

How can I figure out which classes implement this IDatabaseInitializer interface?

Or a more generic example, say I want to know which exact classes implement the ienumerable interface. When looking on msdn the interface description is given, but no reference to classes that actually implement ienumerable.

Thanks.
Web Star replied to Bieters Bieters on 06-Mar-12 11:56 PM
Try this
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
                where t.GetInterfaces().Contains(typeof(ITestInterface))
                         && t.GetConstructor(Type.EmptyTypes) != null
                select Activator.CreateInstance(t) as ITestInterface;


foreach (var instance in instances)
{
    instance.Get(); // where Get is a method of ITestInterface
}


Hope this helps you
Web Star replied to Bieters Bieters on 06-Mar-12 11:57 PM
Also see this artice show you how can get class that implement an interface
http://notes.theorbis.net/2008/01/c-determining-whether-class-implements.html 

hope this helps you
Somesh Yadav replied to Bieters Bieters on 07-Mar-12 12:11 AM

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 off the top if my head.

You could use something like the following and tailor it to your needs.

var _interfaceType = typeof(ISomething);
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var types = GetType().GetNestedTypes();

foreach (var type in types)
{
   
if (_interfaceType.IsAssignableFrom(type) && type.IsPublic && !type.IsInterface)
   
{
       
ISomething something = (ISomething)currentAssembly.CreateInstance(type.FullName, false);
        something
.TheMethod();
   
}
}

This code could use some performance enhancements but it's a start.

Bieters Bieters replied to Somesh Yadav on 07-Mar-12 01:30 AM
Thanks, all.
I've been able to do it via reflection like yours examples.
Sadly msdn doesn't show it somewhere for framework classes.
Somesh Yadav replied to Bieters Bieters on 07-Mar-12 05:50 AM
welcome!