I have an open generic type definition and want to check whether this open definition implements an open interface definition.
interface IMyInterface<T>
{}
class GoodType<T> : IMyInterface<T> where T : Enum
{
}
class BadType<T> where T : Enum
{
}
static bool IsOpenGenericTypeImplementing(Type candidate, Type iface) =>
candidate.IsGenericTypeDefinition &&
candidate.GetGenericArguments().Length == 1 &&
candidate.MakeGenericType(typeof(object)).IsAssignableTo(iface.MakeGenericType(typeof(object))); // does not work
[Fact]
void Test()
{
Assert.True(IsOpenGenericTypeImplementing(typeof(GoodType<>), typeof(IMyInterface<>)));
Assert.False(IsOpenGenericTypeImplementing(typeof(BadType<>), typeof(IMyInterface<>)));
}
The problem with the approach above is that is will fail because of the Enum
type constraint (ArgumentException).
I found some similar questions but all seem to need a closed generic type definition (<T>
instead of <>
).
E.g. Finding out if a type implements a generic interface