Does reflection in C#
offer a way to determine if some given System.Type
type models some interface?
public interface IMyInterface {}
public class MyType : IMyInterface {}
// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
You have a few choices:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
or (as of .NET 5) the equivalent inverse, typeof(MyType).IsAssignableTo(typeof(IMyInterface))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
nameof
operator typeof(MyType).GetInterface(nameof(IMyInterface)) != null
- but beware that nameof
does not return the fully-qualified type name, so if you have multiple interfaces named the same in different namespaces, you may end up getting all of themFor a generic interface, it’s a bit more involved:
Array.Exists(
typeof(MyType).GetInterfaces(),
i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>))
or with LINQ:
typeof(MyType).GetInterfaces().Any(
i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>))