Enum Description


/ Published in: C#
Save to your folder(s)

<p>Returns the description set in an enum value, or if not description is found it returns the name of the enum value. Use this without worrying about passing the enum type, you should only pass the enum value</p>

<p>Example</p>

<pre><code>internal enum Duration
{
[Description("Every 12 Months")] Year = 1
[Description("Every 6 Months")] Semester = 2
}

GetEnumDescription(Duration.Year) returns "Every 12 Months"
</code></pre>


Copy this code and paste it in your HTML
  1. using System.Reflection;
  2. using System.ComponentModel;
  3.  
  4. /// <summary>
  5. /// Returns the enum description (if any), otherwise returns the name of the enum value
  6. /// </summary>
  7. internal static string GetEnumDescription<TEnum>(TEnum enumObj)
  8. {
  9. FieldInfo fi = enumObj.GetType().GetField(enumObj.ToString());
  10. DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  11.  
  12. if (attributes != null && attributes.Length > 0)
  13. {
  14. return attributes[0].Description;
  15. }
  16. else
  17. {
  18. return enumObj.ToString();
  19. }
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.