using System.ComponentModel; using System.Reflection; namespace Common.Helpers; public static class EnumHelpers { /// /// Parse enum from string to enum type. /// /// type of the enum /// value to parse to enum /// returns enum object with value public static T ParseEnum(string value) { return (T)Enum.Parse(typeof(T), value, true); } /// /// Gets the description of an Enum value. /// If there is no Description set, the Enum Value will be converted to string. /// /// Enum Object to get Description of. /// String with Content of DescriptionAttribute of Enum object. public static string GetEnumDescription(Enum enumObject) { // guard argument null if (enumObject == null) { throw new ArgumentNullException(nameof(enumObject)); } // get field info from enum type FieldInfo? fieldInfo = enumObject.GetType().GetField(enumObject.ToString()); // return string of enum value if there is no field info if (fieldInfo == null) { return enumObject.ToString(); } // get description attribute and return if it is present DescriptionAttribute? descAttrib = (DescriptionAttribute?)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute), true); if (descAttrib != null) { return descAttrib.Description; } // if no description attribute was found => return string of enum value return enumObject.ToString(); } }