Search code examples
c#reflectioninterface

How to determine if a type implements an interface with C# reflection


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:

    1. typeof(IMyInterface).IsAssignableFrom(typeof(MyType)) or (as of .NET 5) the equivalent inverse, typeof(MyType).IsAssignableTo(typeof(IMyInterface))
    2. typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
    3. With C# 6+ you can use the 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 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<>))