Programatically checking whether a type implements a interface?

Hi all,

How can i programatically find whether a type is marked with an attribute or it implements an interface

For ex:

[Serializable]
class MyClass : ISerializable
{
}

If my function get this type as input it should tell me whether it is marked with any attribute or it implements any interface.

Thanks,
Suresh.


Answer this question

Programatically checking whether a type implements a interface?

  • Mal

    I'd do it like this:


    bool hasAttribute = typeof(MyClass).IsSerializable;

    bool implementsInterface = typeof(ISerializable).IsAssignableFrom(typeof(MyClass));


     


  • jackerliu

    Reflection will help:



    bool hasAttribute = typeof(MyClass).GetCustomAttributes(typeof(SerializableAttribute), true).Length > 0;

    bool implementsInterface = typeof(MyClass).GetInterface(typeof(ISerializable).FullName, false) != null;

     


  • Programatically checking whether a type implements a interface?