Wednesday, 4 October 2017

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);

Answer




You have a few choices:




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


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




For a generic interface, it’s a bit different.



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


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...