Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsAssignableFrom when interface has generics, but not the implementation

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?

like image 293
Allrameest Avatar asked May 30 '11 10:05

Allrameest


1 Answers

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.

like image 84
Oliver Avatar answered Nov 14 '22 22:11

Oliver