-
-
Save schourode/1099072 to your computer and use it in GitHub Desktop.
GetDisplayNameFor<MyType>(x=>x.MyProperty);
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DisplayNameHelper | |
{ | |
/// <summary> | |
/// Get the DataAnnotation attributed DisplayName attribute value. | |
/// </summary> | |
/// <example> | |
/// GetDisplayNameFor<VagtTyper>(x => x.Doegnvagt) ==> "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