Coder Perfect

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

Problem

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:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));

Answered by Snea

Solution #3

typeof(IMyInterface).IsAssignableFrom(someclass.GetType());

or

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));

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.

Usage:

if(MyType.Implements<IInitializable>())
  MyCollection.Initialize();

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

Answered by toddmo

Post is based on https://stackoverflow.com/questions/4963160/how-to-determine-if-a-type-implements-an-interface-with-c-sharp-reflection