How to check if a generic type definition inherits from another generic type definition
- by Anne
I'm trying to check whether an open generic type definition implements some open generic interface. Look at the sample below:
public interface IService<T> { }
public class ServiceImpl<T> : IService<T> { }
private static bool OpenGenericTypeImplementsOpenGenericInterface(
Type derivedType, Type interfaceType)
{
return derivedType.GetInterfaces().Contains(interfaceType);
}
[TestMethod]
public void Verify()
{
Type openGenericImplementation = typeof(ServiceImpl<>);
Type expectedInterfaceType = typeof(IService<>);
bool implDoesImplementInterface = OpenGenericTypeImplementsOpenGenericInterface(
openGenericImplementation, expectedInterfaceType);
// This assert fails. Why?
Assert.IsTrue(implDoesImplementInterface);
}
I found out that the returned type from the Type.GetInterfaces() method does not match the type returned from typeof(IService<>). I can't figure out why that is and how to correctly validate whether some generic type definition inherits or implements some other generic type definition.
What's going on here and how do I solve fix this problem?