Posted By

dotNetkow on 11/19/10


Tagged

enum c# SystemComponentModel


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

pavelhodek


Allow enums to have spaces


 / Published in: C#
 

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

  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  

You need to login to post a comment.