In order to get more “readable” descriptions for the enumerations (for example, “Very High”, and not “VeryHigh” in your example), I decorated the enum values with an attribute as follows:
public enum MeasurementType { Each, [DisplayText("Lineal Metres")] LinealMetre, [DisplayText("Square Metres")] SquareMetre, [DisplayText("Cubic Metres")] CubicMetre, [DisplayText("Per 1000")] Per1000, Other } public class DisplayText : Attribute { public DisplayText(string Text) { this.text = Text; } private string text; public string Text { get { return text; } set { text = value; } } }
Then the extension method is used as follows:
public static string ToDescription(this Enum en) { Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes( typeof(DisplayText), false); if (attrs != null && attrs.Length > 0) return ((DisplayText)attrs[0]).Text; } return en.ToString(); }
Then you can just call
myEnum.ToDescription ()
to display your listing as more readable text.
Stuart Helwig Aug 09 2018-10-09T00: 00Z
source share