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

19,164

Solution 1

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.

Solution 2

Check out IsAssignableFrom http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

Solution 3

Hi You can use type.GetInterfaces() or type.GetInterface() to get the interfaces which the type implements.

Share:
19,164
iburlakov
Author by

iburlakov

.net developer

Updated on June 02, 2022

Comments

  • iburlakov
    iburlakov about 2 years

    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.