5

I've searched for this and found this: How To Detect If Type is Another Generic Type

The problem with this solution is that it expects the implementation to have the same type parameters. What I want is to see if a class implements an interface with any type parameter.

Example:

public interface IMapper<in TSource, out TDestination>
{ ... }

public class StringMapper : IMapper<string, StringBuilder>
{ ... }

Console.WriteLine(typeof(IMapper<,>).IsAssignableFrom(typeof(StringMapper)));

I want this to write true, but it writes false. How can I check if a class implements an interface with generic parameters?

Community
  • 1
  • 1
Allrameest
  • 4,364
  • 2
  • 34
  • 50

2 Answers2

8

I think you have to call GetInterfaces() from your StringMapper and test each one for IsGenericType. Last but not least get the open type (IMapper<,>) of each generic one by calling GetGenericTypeDefinition() and test if it matches typeof(IMapper<,>).

That's all you can do. But be aware, if the class inherits from another base class which also implements some interfaces, these won't be listed. In that case you have to recursevly run down through the BaseType properties and do the above down till the BaseType is null.

Oliver
  • 43,366
  • 8
  • 94
  • 151
  • Seems like GetInterfaces() actually includes all interfaces, even those implemented by base classes. I've edited that and included some code. Will accept it after the edit has been accepted. :) – Allrameest May 30 '11 at 11:29
  • ok, than was the recursive not needed for interfaces, but there was something (currently don't know what) that needed to be explicitly asked to the base class or you get the wrong results. – Oliver May 30 '11 at 11:59
  • Maybe if you don't have a generic interface, but generic base class. Then you would have to some looping/recursion. But right now I'm only looking for interfaces... – Allrameest May 30 '11 at 12:22
5

Worked like a charm for me. Here's a code snippet in case anyone's interested:

    IEnumerable<Type> reports =
        from type in GetType().Assembly.GetTypes()
        where
            type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IReport<>)) &&
            type.IsClass
        select type;
Kristopher
  • 435
  • 5
  • 8