13

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,

Houman
  • 64,245
  • 87
  • 278
  • 460

1 Answers1

25

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;
}
Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53
  • 7
    If you are using resource files you will need to use the `GetName()` method, not just the `Name` property i.e. the 2nd last line would be return `((DisplayAttribute)displayAttributes[0]).GetName();` – Dennis Sheen Dec 17 '12 at 00:56
  • The null check for displayAttributes != null is probably not needed here, as GetCustomAttributes always returns an object[] – Michiel Cornille Apr 20 '16 at 14:27