Home >Backend Development >C++ >How Can I Get User-Friendly Strings from Enums in C#?
Displaying Enums with Human-Readable Strings in C#
Enums are valuable for representing named constants, but directly displaying their values often lacks clarity for users. This guide demonstrates how to map enum values to user-friendly strings without the reverse string-to-value conversion.
The solution leverages the Description
attribute from System.ComponentModel
. By applying this attribute to your enum members, you provide a more descriptive label for each value.
Example:
<code class="language-csharp">private enum PublishStatusValue { [Description("Not Completed")] NotCompleted, Completed, Error }</code>
Retrieving User-Friendly Strings:
The following extension method retrieves the description or the enum's default string representation if no description is found:
<code class="language-csharp">public static string GetDescription<T>(this T enumerationValue) where T : struct { Type type = enumerationValue.GetType(); if (!type.IsEnum) { throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue"); } MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString()); if (memberInfo != null && memberInfo.Length > 0) { object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) { return ((DescriptionAttribute)attrs[0]).Description; } } return enumerationValue.ToString(); }</code>
This method efficiently provides user-friendly output, enhancing code readability and user experience.
The above is the detailed content of How Can I Get User-Friendly Strings from Enums in C#?. For more information, please follow other related articles on the PHP Chinese website!