Home >Backend Development >C++ >Can I Assign Friendly Names to Enum Members in C#?

Can I Assign Friendly Names to Enum Members in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-19 11:12:09724browse

Can I Assign Friendly Names to Enum Members in C#?

Can C# enums use friendly names?

As you discovered, C# enumeration members can only have literal names, with underscores as delimiters. However, there is a way to assign a "friendly name" to your enumeration.

Solution: Description attribute

You can use the DescriptionAttribute attribute to provide a friendlier description for each enumeration member. Here is an extension method that simplifies retrieving descriptions:

<code class="language-csharp">public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    FieldInfo field = type.GetField(name);
    DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
    return attr != null ? attr.Description : null;
}</code>

Usage:

Apply DescriptionAttribute to each enum member and provide the desired friendly name:

<code class="language-csharp">public enum MyEnum
{
    [Description("此名称有效")]
    ThisNameWorks,
    [Description("此名称无效")]
    ThisNameDoesntWork,
    [Description("这个也不行")]
    NeitherDoesThis
}</code>

To retrieve friendly names:

<code class="language-csharp">MyEnum x = MyEnum.ThisNameWorks;
string description = x.GetDescription();</code>

The above is the detailed content of Can I Assign Friendly Names to Enum Members in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn