Get enum description


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

Description attribute retrieval using an extension method.


Copy this code and paste it in your HTML
  1. public enum PaymentTypes
  2. {
  3. [Description("Mooring Licence Fee")]
  4. MooringLicenceFee = 1,
  5. Contact = 2,
  6. Vessel = 3,
  7. Enquiry = 4,
  8. [Description("Inspection Entry")]
  9. InspectionEntry = 5,
  10. Lease = 6,
  11. [Description("Licence Transfer")]
  12. LicenceTransfer = 7,
  13. Other = 8
  14. }
  15.  
  16. public static class Extensions
  17. {
  18. public static string GetDescription(this PaymentTypes value)
  19. {
  20. Type type = value.GetType();
  21. string name = Enum.GetName(type, value);
  22. if (name != null)
  23. {
  24. FieldInfo field = type.GetField(name);
  25. if (field != null)
  26. {
  27. DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
  28. if (attr == null)
  29. {
  30. return name;
  31. }
  32. else
  33. {
  34. return attr.Description;
  35. }
  36. }
  37. }
  38. return null;
  39.  
  40. }
  41. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.