Posted By

dimitrisdapontes on 01/26/13


Tagged

enum description


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

emregulcan
danfinrud55


Enum Description


 / Published in: C#
 

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

Example

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

GetEnumDescription(Duration.Year) returns "Every 12 Months"
  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  

You need to login to post a comment.