How Can I Get User-Friendly Strings from Enums in C#?
Jan 23, 2025 am 03:47 AMDisplaying 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:
private enum PublishStatusValue { [Description("Not Completed")] NotCompleted, Completed, Error }
Retrieving User-Friendly Strings:
The following extension method retrieves the description or the enum's default string representation if no description is found:
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(); }
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

C language function format letter case conversion steps

What are the definitions and calling rules of c language functions and what are the

Where is the return value of the c language function stored in memory?

How does the C Standard Template Library (STL) work?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?
