Note that if you have a generic interface IMyInterface<T>
then this will always return false
:
typeof(IMyInterface<>).IsAssignableFrom(typeof(MyType)) /* ALWAYS FALSE */
This doesn't work either:
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface<>)) /* ALWAYS FALSE */
However, if MyType
implements IMyInterface<MyType>
this works and returns true
:
typeof(IMyInterface<MyType>).IsAssignableFrom(typeof(MyType))
However, you likely will not know the type parameter T
at runtime. A somewhat hacky solution is:
typeof(MyType).GetInterfaces()
.Any(x=>x.Name == typeof(IMyInterface<>).Name)
Jeff's solution is a bit less hacky:
typeof(MyType).GetInterfaces()
.Any(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>));
Here's a extension method on Type
that works for any case:
public static class TypeExtensions
{
public static bool IsImplementing(this Type type, Type someInterface)
{
return type.GetInterfaces()
.Any(i => i == someInterface
|| i.IsGenericType
&& i.GetGenericTypeDefinition() == someInterface);
}
}
(Note that the above uses linq, which is probably slower than a loop.)
You can then do:
typeof(MyType).IsImplementing(IMyInterface<>)