Search code examples
c#reflectioninheritanceinterface

How to check that type is inherited from some interface c#


I have following:

Assembly asm = Assembly.GetAssembly(this.GetType());

foreach (Type type in asm.GetTypes())
{
    MyAttribute attr = Attribute.GetCustomAttribute(type, typeof(MyAttribute))    as MyAttribute;
     if(attr != null && [type is inherited from Iinterface])
     {
        ...
     }

}

How can i check that type is inherited from MyInterface? Does is keywork will work in this way?

Thank you.


Solution

  • No, is only works for checking the type of an object, not for a given Type. You want Type.IsAssignableFrom:

    if (attr != null && typeof(IInterface).IsAssignableFrom(type))
    

    Note the order here. I find that I almost always use typeof(...) as the target of the call. Basically for it to return true, the target has to be the "parent" type and the argument has to be the "child" type.