.NET - Getting all implementations of a generic interface?

An answer on " Implementations of interface through Reflection " shows how to get all implementations of an interface. However, given a generic interface, IInterface<T>, the following doesn't work:

var types = TypesImplementingInterface(typeof(IInterface<>))

Can anyone explain how I can modify that method?

Answers


You can use something like this:

public static bool DoesTypeSupportInterface(Type type, Type inter)
{
    if(inter.IsAssignableFrom(type))
        return true;
    if(type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))
        return true;
    return false;
}

public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
    return AppDomain
        .CurrentDomain
        .GetAssemblies()
        .SelectMany(assembly => assembly.GetTypes())
        .Where(type => DoesTypeSupportInterface(type, desiredType));

}

It can throw a TypeLoadException though but that's a problem already present in the original code. For example in LINQPad it doesn't work because some libraries can't be loaded.


It doesn't work because IInterface<object> (using System.Object for T as an example) doesn't inherit from the "open" generic type IInterface<>. A "closed" generic type is a root type, just like IFoo. You can only search for closed generic types, not open ones, meaning you could find everything that inherits from IInterface<int>. IFoo does not have a base class, nor does IInterface<object> or IInterface<string> etc.


Need Your Help

How do I apply a perspective transform to a UIView?

ios cocoa-touch core-animation

I'm looking to perform a perspective transform on a UIView (such as seen in coverflow)

How to remove a dependency from my Android project in Eclipse

android eclipse dependencies libraries

When I highlight my project, go to properties, select java build path and then try to remove an Android Dependency from my list of Android dependencies the remove button is grey'd out. How can I re...