Coder Perfect

With C# reflectio, how can I tell if a type implements an interface?


Is there a method to tell if a System.Type type models a specific interface in C# reflection?

public interface IMyInterface {}

public class MyType : IMyInterface {}

// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);

Asked by Yippie-Ki-Yay

Solution #1

There are a few options available to you:

It’s a little different for a generic interface.

typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))

Answered by Jeff

Solution #2

Use Type.IsAssignableFrom:


Answered by Snea

Solution #3




Answered by ajma

Solution #4

public static bool ImplementsInterface(this Type type, Type ifaceType) 
    Type[] intf = type.GetInterfaces();
    for(int i = 0; i < intf.Length; i++) 
        if(intf[ i ] == ifaceType) 
            return true;
    return false;

This is the correct release, in my opinion, for three reasons:

Answered by Panos Theof

Solution #5

I just did:

public static bool Implements<I>(this Type source) where I : class
  return typeof(I).IsAssignableFrom(source);

I wish I could have said where I: interface, but interface is not a parameter constraint option that can be applied to any parameter. As near as it gets is class.



Because it’s more intuitive, I just said Implements. IsAssignableFrom is constantly flip-flopped for me.

Answered by toddmo

Post is based on