Skip to content

Instantly share code, notes, and snippets.

@schourode
Forked from dalager/DisplayNameHelper.cs
Created July 22, 2011 08:14
Show Gist options
  • Save schourode/1099072 to your computer and use it in GitHub Desktop.
Save schourode/1099072 to your computer and use it in GitHub Desktop.
GetDisplayNameFor<MyType>(x=>x.MyProperty);
public class DisplayNameHelper
{
/// <summary>
/// Get the DataAnnotation attributed DisplayName attribute value.
/// </summary>
/// <example>
/// GetDisplayNameFor&lt;VagtTyper&gt;(x =&gt; x.Doegnvagt) ==&gt; "Døgnvagt"
/// </example>
/// <typeparam name="TSource">The type you wish to work on</typeparam>
/// <typeparam name="TProp">The type of the property</typeparam>
/// <param name="propLambda">Property selector for that type</param>
/// <returns>The DisplayName or the propertyname if no DisplayNameAttribute was set</returns>
public string GetDisplayNameFor<TSource, TProp>(Expression<Func<TSource, TProp>> propLambda)
{
var member = propLambda.Body as MemberExpression;
if (member == null) throw new ArgumentException("No methods, please!");
var propertyInfo = member.Member as PropertyInfo;
if (propertyInfo == null) throw new ArgumentException("No fields, please!");
var dna = propertyInfo
.GetCustomAttributes(typeof(DisplayNameAttribute), true)
.OfType<DisplayNameAttribute>()
.FirstOrDefault();
return dna == null ? propertyInfo.Name : dna.DisplayName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment