/// <summary> /// Gets the description from a given enum value. /// </summary> /// <param name="value">The value.</param> /// <param name="IsDisplayError">if set to <c>true</c> [is display error].</param> /// <returns> /// System.String. /// </returns> public static string GetEnumDescription(this Enum value, bool IsDisplayError = true) { ErrorBase.CheckArgIsNull(value, () => value); string description = null; var enumType = value.GetType(); var fi = enumType.GetField(value.ToString()); var customAttributeTypes = new List <Type> { typeof(EnumDescriptionAttribute), typeof(EnumMemberAttribute), typeof(DescriptionAttribute), }; var myEnumAttribute = fi.GetCustomAttributes(true) .FirstOrDefault(A => customAttributeTypes.Contains(A.GetType())); if (null == myEnumAttribute) { if (IsDisplayError) { ErrorBase.Require(false, $"The given enum value {value} does not have DescriptionAttribute!"); } return(description); } if (typeof(EnumDescriptionAttribute) == myEnumAttribute.GetType()) { description = ((EnumDescriptionAttribute)myEnumAttribute).Description; } else if (typeof(EnumMemberAttribute) == myEnumAttribute.GetType()) { description = ((EnumMemberAttribute)myEnumAttribute).Value; } else if (typeof(DescriptionAttribute) == myEnumAttribute.GetType()) { description = ((DescriptionAttribute)myEnumAttribute).Description; } return(description); }
/// <summary> /// Gets the description from a given enum value. /// </summary> /// <typeparam name="TAttribute">The type of the attribute.</typeparam> /// <param name="value">The value.</param> /// <param name="IsDisplayError">if set to <c>true</c> [is display error].</param> /// <returns> /// System.String. /// </returns> public static string GetEnumDescription <TAttribute>(this Enum value, bool IsDisplayError = true) where TAttribute : Attribute { ErrorBase.CheckArgIsNull(value, () => value); string output = null; var type = value.GetType(); var fi = type.GetField(value.ToString()); //Hp --> Logic: Look for our 'TAttr' in the field's custom attributes var myAttributes = fi.GetCustomAttributes <TAttribute>(false); //Hp --> Logic: Only single instance of 'EnumDescriptionAttribute' is allowed. var myEnumAttribute = myAttributes?.SingleOrDefault(); if (myEnumAttribute != null) { if (typeof(EnumDescriptionAttribute) == myEnumAttribute.GetType()) { output = (myEnumAttribute as EnumDescriptionAttribute).Description; } else if (typeof(EnumMemberAttribute) == myEnumAttribute.GetType()) { output = (myEnumAttribute as EnumMemberAttribute).Value; } else if (typeof(DescriptionAttribute) == myEnumAttribute.GetType()) { output = (myEnumAttribute as DescriptionAttribute).Description; } } else { if (IsDisplayError) { ErrorBase.Require(false, $"The given enum value {value} does not have DescriptionAttribute!"); } } return(output); }