Tuesday, February 7, 2017

check for interfaces in c#

today an interesting question about interfaces came up. Does reflection's GetInterfaces() return all interfaces of all hierarchical levels?

    public interface ILevel1{}
    public interface ILevel2 : ILevel1, IAdditionalInterface2{}
    public interface ILevel3 : ILevel2{}
    public interface IAdditionalInterface {}
    public interface IAdditionalInterface2 { }
    public class MyClass : ILevel3, IAdditionalInterface {}

The answer is yes: it does!

MyClass implements any interface which can be tested using the 
  • "is"-operator (INSTANCE is INTERFACE_TO_CHECK) or 
  • INSTANCE.GetType().GetInterfaces().Contains(typeof( INTERFACE_TO_CHECK ))
both methods return the same.


No comments: