Skip to content

Instantly share code, notes, and snippets.

@dalager
Created July 22, 2011 07:56
Show Gist options
  • Save dalager/1099049 to your computer and use it in GitHub Desktop.
Save dalager/1099049 to your computer and use it in GitHub Desktop.
GetDisplayNameFor<MyType>(x=>x.MyProperty);
/// <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"></typeparam>
/// <param name="propLambda"></param>
/// <returns></returns>
public string GetDisplayNameFor<TSource>(Expression<Func<TSource,object>> propLambda)
{
var expression = propLambda.Body;
var unaryExp = expression as UnaryExpression;
if (unaryExp != null)
{
var memberExp = (MemberExpression)unaryExp.Operand;
var dna = memberExp.Member
.GetCustomAttributes(typeof(DisplayNameAttribute), true)
.Cast<DisplayNameAttribute>()
.FirstOrDefault();
return dna == null ? memberExp.Member.Name : dna.DisplayName;
}
throw new ArgumentException("Only properties can be used in this method");
}
@dalager
Copy link
Author

dalager commented Jul 22, 2011

A quick take on using the System.ComponentModel.DataAnnotations.DisplayNameAttribute like this:

var displayName = GetDisplayNameFor(x=>x.MyProperty);

Where

class MyType{
[DisplayName("Something Foo")]
public bool MyProperty{get;set;}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment