During development sometimes we come across the situation to get the enum
specification, means list of available Name, Value or attribute description (if
available).
Here are the sample methods to get these enum details: (C# code
example)
////// Get all the values Description of this Enum /// ///enum type ///public static List GetDescrptionList () where TEnum : struct { if (!typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); } var enumType = typeof(TEnum); var enumDescriptionList = new List (); foreach (var value in Enum.GetValues(enumType)) { var enumDescription = GetDescription((Enum)value); enumDescriptionList.Add(enumDescription); } return enumDescriptionList; } /// /// Get the description field of this Enum value /// /// Value of enum ///public static string GetDescription(Enum value) { var fi = value.GetType().GetField(value.ToString()); var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : value.ToString(); } /// /// Get list of values (1,2,3) /// ////// public static List GetValues () where TEnum : struct { if (!typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); } var enumType = typeof(TEnum); var enumValues = new List (); foreach (var value in Enum.GetValues(enumType)) { enumValues.Add((int)value); } return enumValues; } /// /// Get names of Enum (e.g.: Contract, Permanent, Intern...) /// ////// public static List GetNames () where TEnum : struct { if (!typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); } var enumType = typeof(TEnum); return Enum.GetNames(enumType).ToList(); } /// /// Get the Name + Value pair list /// ////// public static List > GetNameValuePairs () { if (!typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); } var enumType = typeof(TEnum); var enumNameDescriptionPair = new List >(); foreach (var value in Enum.GetValues(enumType)) { var intValue = (int)value; enumNameDescriptionPair.Add(new KeyValuePair (value.ToString(), intValue)); } return enumNameDescriptionPair; }
Assume we've EmployeeTypes as enum like this:
public enum EmployeeType { Permanent, Intern, [Description("Contract type employee")] Contract }
Example to use this
var desc = EnumUtilities.GetDescription(EmployeeType.Contract); // Result: // Contract type employee var names = EnumUtilities.GetNames(); // Result: // Permanent // Intern // Contract var values = EnumUtilities.GetValues (); // Result: // 0 // 1 // 2
Comments
Post a Comment