Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 344
Houman Avatar asked Mar 31 '11 11:03

Houman


1 Answers

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;
}
like image 54
Florian Greinacher Avatar answered Oct 07 '22 16:10

Florian Greinacher