Allow enums to have spaces


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

By default, enum values cannot have spaces in them (i.e. "Created Date" can only be "CreatedDate"). With this method, we can change that!


Copy this code and paste it in your HTML
  1. using System.ComponentModel;
  2.  
  3. public class MyClass
  4. {
  5. /// <summary>
  6. /// Returns the description attribute of an Enum if available, othewise returns
  7. /// the toString() of the value passed in.
  8. ///
  9. /// Useful for Enums with spaces in them.
  10. /// </summary>
  11. /// <param name="value">the enum</param>
  12. /// <returns>the description string of the enum</returns>
  13. public static string GetEnumDescription(Enum value)
  14. {
  15. FieldInfo fi = value.GetType().GetField(value.ToString());
  16.  
  17. DescriptionAttribute[] attributes =
  18. (DescriptionAttribute[])fi.GetCustomAttributes(
  19. typeof(DescriptionAttribute),false);
  20.  
  21. if (attributes != null && attributes.Length > 0)
  22. return attributes[0].Description;
  23. else
  24. return value.ToString();
  25. }
  26. }
  27.  
  28. public enum Types
  29. {
  30. [Description("Created Date")]
  31. CreatedDate,
  32. Description,
  33. Test
  34. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.