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
Release: 2025-01-19 11:12:09
Original
726 people have browsed it

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:

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;
}
Copy after login

Usage:

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

public enum MyEnum
{
    [Description("此名称有效")]
    ThisNameWorks,
    [Description("此名称无效")]
    ThisNameDoesntWork,
    [Description("这个也不行")]
    NeitherDoesThis
}
Copy after login

To retrieve friendly names:

MyEnum x = MyEnum.ThisNameWorks;
string description = x.GetDescription();
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template