× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

C#: How to get the value of any Attribute applied to an Enum member.

Apr 14, 2016
<p>This little extension method will help you retrieve the value of any attribute that is applied to an enum member!</p> <pre><code class="language-cs">public static class Extensions { public static TAttribute GetAttribute&lt;TAttribute&gt;(this Enum enumValue) where TAttribute : Attribute { return enumValue.GetType() .GetMember(enumValue.ToString()) .First() .GetCustomAttribute&lt;TAttribute&gt;(); } }</code></pre> <p><span dir="ltr">And here's an example of it being used with <span class="marker">the [Display] attribute</span></span></p> <pre><code class="language-cs">void Main() { DisplayAttribute seasonDisplayName = Season.Winter.GetAttribute&lt;DisplayAttribute&gt;(); Console.WriteLine (seasonDisplayName.Name); // "It's winter } public enum Season { [Display(Name = "It's autumn")] Autumn, [Display(Name = "It's winter")] Winter, [Display(Name = "It's spring")] Spring, [Display(Name = "It's summer")] Summer }</code></pre> <p> </p>
comments powered by Disqus