Omu
Omu

Reputation: 71188

check if type has or inherit a type that has a certain attribute

I'm trying to check if a type has the [DataContract] attribute defined or inherits a type that has it defined

for instance:

[DataContract]
public class Base
{
}


public class Child : Base
{
}

// IsDefined(typeof(Child), typeof(DataContract)) should be true;

the Attribute.IsDefined, and Attribute.GetCustomAttribute doesn't look at the base class

anybody knows how to do this without looking at the BaseClasses

Upvotes: 0

Views: 216

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

Try this

public static bool IsDefined(Type t, Type attrType)
{
    do {
        if (t.GetCustomAttributes(attrType, true).Length > 0) {
            return true;
        }
        t = t.BaseType;
    } while (t != null);
    return false;
}

I got the idea to make it with a recursive call because of the term "recursion" in your comment. Here is an extension method

public static bool IsDefined(this Type t, Type attrType)
{
    if (t == null) {
        return false;
    }
    return 
        t.GetCustomAttributes(attrType, true).Length > 0 ||
        t.BaseType.IsDefined(attrType);
}

call it like this

typeof(Child).IsDefined(typeof(DataContractAttribute))

Upvotes: 1

Dmitry S.
Dmitry S.

Reputation: 8503

There is an overload on the GetCustomAttribute() and GetCustomAttributes(bool inherit) methods that takes a bool value whether to do a search in inherited classes. However, it will only work if the attribute you are searching for was defined with the [AttributeUsage(AttributeTargets.?, Inherited = true)] attribute.

Upvotes: 4

Related Questions