I think Enums are quite useful. I wrote several extensions for Enum that added even more value to use
Firstly, there is a method for expanding the description
public static class EnumExtensions { public static string Description(this Enum value) { var entries = value.ToString().Split(ENUM_SEPERATOR_CHARACTER); var description = new string[entries.Length]; for (var i = 0; i < entries.Length; i++) { var fieldInfo = value.GetType().GetField(entries[i].Trim()); var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); description[i] = (attributes.Length > 0) ? attributes[0].Description : entries[i].Trim(); } return String.Join(", ", description); } private const char ENUM_SEPERATOR_CHARACTER = ','; }
This will allow me to define en enum as follows:
public enum MeasurementUnitType { [Description("px")] Pixels = 0, [Description("em")] Em = 1, [Description("%")] Percent = 2, [Description("pt")] Points = 3 }
And get the label by doing the following: var myLabel = rectangle.widthunit.Description() (eliminating the need for a switch ).
This will return "px" if rectangle.widthunit = MeasurementUnitType.Pixels or it will return "px, em" if rectangle.widthunit = MeasurementUnitType.Pixels | MeasurementUnitType.Em rectangle.widthunit = MeasurementUnitType.Pixels | MeasurementUnitType.Em .
Then there is
public static IEnumerable<int> GetIntBasedEnumMembers(Type @enum) { foreach (FieldInfo fi in @enum.GetFields(BindingFlags.Public | BindingFlags.Static)) yield return (int)fi.GetRawConstantValue(); }
Which will allow me to go through any enum with int-based values and return the int values themselves.
I find that they are very useful in the helpful allready concept.
danijels Oct 12 2018-10-12 10:34
source share