Houman
Houman

Reputation: 66320

How to get DisplayAttribute of a property by Reflection?

I have a Helper method like this to get me the PropertyName (trying to avoid magic strings)

public static string GetPropertyName<T>(Expression<Func<T>> expression)
        {
            var body = (MemberExpression) expression.Body;
            return body.Member.Name;
        }

However sometimes my PropertyNames aren't named well either. So I would like to rather use the DisplayAttribute.

[Display(Name = "Last Name")]
public string Lastname {get; set;}

Please be aware I am using Silverlight 4.0. I couldnt find the usual namespace DisplayAttributeName attribute for this.

How can I change my method to read the attribute (if available) of th eproperty instead?

Many Thanks,

Upvotes: 14

Views: 9885

Answers (1)

Florian Greinacher
Florian Greinacher

Reputation: 14784

This should work:

public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression propertyExpression = (MemberExpression)expression.Body;
    MemberInfo propertyMember = propertyExpression.Member;

    Object[] displayAttributes = propertyMember.GetCustomAttributes(typeof(DisplayAttribute), true);
    if(displayAttributes != null && displayAttributes.Length == 1)
        return ((DisplayAttribute)displayAttributes[0]).Name;

    return propertyMember.Name;
}

Upvotes: 26

Related Questions