Yippie-Ki-Yay Yippie-Ki-Yay - 1 year ago 115
C# Question

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

Does reflection in

offer a way to determine if some given
type models some interface?

public interface IMyInterface {}

public class MyType : IMyInterface {}

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

Answer Source

You have a few choices off the top of my head

  1. typeof(IMyInterface).IsAssignableFrom(typeof(MyType))

  2. typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download