20

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?

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way around the TypeLoader exception?
You can try catching it. But when I tried that linqpad crashed.
GetInterfaces() doesn't return interfaces implemented by a parent class, does it? Do I need to recursively look at parent classes until I hit typeof(System.Object)?
@DavidPfeffer It includes inherited interfaces: GetInterfaces() returns "all the interfaces implemented or inherited by the current Type."
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.