snippetcsharpCritical
How to determine if a type implements an interface with C# reflection
Viewed 0 times
withhowimplementsdetermineinterfacereflectiontype
Problem
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);Solution
You have a few choices:
For a generic interface, it’s a bit more involved:
or with LINQ:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))or (as of .NET 5) the equivalent inverse,typeof(MyType).IsAssignableTo(typeof(IMyInterface))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
- With C# 6+ you can use the
nameofoperatortypeof(MyType).GetInterface(nameof(IMyInterface)) != null- but beware thatnameofdoes 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 them
For 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<>))Code Snippets
Array.Exists(
typeof(MyType).GetInterfaces(),
i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>))typeof(MyType).GetInterfaces().Any(
i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IMyInterface<>))Context
Stack Overflow Q#4963160, score: 1273
Revisions (0)
No revisions yet.