mkus
mkus

Reputation: 3487

How to determine whether an interface type implements a custom attibute

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

Upvotes: 0

Views: 91

Answers (3)

user1228
user1228

Reputation:

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));
}

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245389

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

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

Upvotes: -1

Samuel Neff
Samuel Neff

Reputation: 74899

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.

Upvotes: 5

Related Questions