views:

33

answers:

3

Hi,

How to determine whether an interface type implements a custom attibute?

+5  A: 

Use GetCustomAttributes:

typeof(IWhatever).GetCustomAttributes(typeof(CustomAttribute), false)

Will return an array of attributes. Empty if it doesn't implement the one you're searching for.

Sam
A: 
Type iType = typeof(IMyInterface);
var attributes = iType.GetCustomAttributes(typeof(MyCustomAttribute), true);

If attributes is empty, then the Interface doesn't implement your attribute.

Justin Niessner
A: 

Try this on for size:

private static bool HasAttribute(this Type me, Type attribute)
{
    if (!typeof(Attribute).IsAssignableFrom(attribute))
        throw new ArgumentException("attribute does not extend System.Attribute.");
    return me.GetCustomAttributes(attribute, true).Length > 0;
}
private static bool HasAttribute<T>(this Type me) where T : System.Attribute
{
    return me.HasAttribute(typeof(T));
}
Will
(null checks are for wusses!)
Will