tags:

views:

244

answers:

3

Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:

    [IsNotNullable]
    [IsPK]
    [IsIdentity]
    [SequenceNameAttribute("Id")]
    public Int32 Id
    {
        get
        {
            return _Id;
        }
        set
        {
            _Id = value;
        }
    }

What is the fastest method to determine that for example it has the "IsIdentity" attribute?

+2  A: 

There's no fast in retrieving attributes. But code ought to look like this:

    Type t = typeof(YourClass)
    PropertyInfo pi = t.GetProperty("Id");
    IsIdentity[] attr = pi.GetCustomAttributes(typeof(IsIdentity), false) as IsIdentity[];
    bool hasIsIdentity = attr.Length > 0;
Hans Passant
If you only need to check for the existence of the attribute, and not retrieve any information from it, using `Attribute.IsDefined` will eliminate one line of code and the ugly arrays/casting.
Aaronaught
+3  A: 

If you are using .NET 3.5 you might try with Expression trees. It is safer than reflection:

class CustomAttribute : Attribute { }

class Program
{
    [Custom]
    public int Id { get; set; }

    static void Main()
    {
        Expression<Func<Program, int>> expression = p => p.Id;
        var memberExpression = (MemberExpression)expression.Body;
        bool hasCustomAttribute = memberExpression
            .Member
            .GetCustomAttributes(typeof(CustomAttribute), false).Length > 0;
    }
}
Darin Dimitrov
+2  A: 

You can use a common (generic) method to read attribute over a given MemberInfo

public static bool TryGetAttribute<T>(MemberInfo memberInfo, out T customAttribute) where T: Attribute {
                var attributes = memberInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
                if (attributes == null) {
                    customAttribute = null;
                    return false;
                }
                customAttribute = (T)attributes;
                return true;
            }
Amby