Home >Backend Development >C++ >How Can I Improve Enum Readability by Using Custom Descriptions?

How Can I Improve Enum Readability by Using Custom Descriptions?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-19 11:22:10498browse

How Can I Improve Enum Readability by Using Custom Descriptions?

Boosting Enum Readability: Using Custom Descriptions

A previous discussion covered assigning descriptive names to enum values. To elaborate:

While the example enum contains values with spaces and periods, enum names must follow specific naming conventions—typically single words without punctuation or spaces.

For more user-friendly enum values, leverage the Description attribute. This attribute lets you add a descriptive string to each enum member, significantly improving code clarity.

Here's a helpful extension method to easily retrieve these descriptions:

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

This method simplifies accessing the description of any enum value. See the example below:

<code class="language-csharp">public enum MyEnum
{
    [Description("Description for Foo")]
    Foo,
    [Description("Description for Bar")]
    Bar
}

MyEnum x = MyEnum.Foo;
string description = x.GetDescription();</code>

The above is the detailed content of How Can I Improve Enum Readability by Using Custom Descriptions?. 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