How to check if a generic type definition inherits from another generic type definition
Posted
by
Anne
on Stack Overflow
See other posts from Stack Overflow
or by Anne
Published on 2011-01-06T19:25:13Z
Indexed on
2011/01/06
19:54 UTC
Read the original article
Hit count: 501
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?
© Stack Overflow or respective owner