[C#] Retrieving Attribute Values Assigned to Enum Members to Change Display Names

When displaying Enums in a UI (such as dropdown lists or labels), you often want to show a user-friendly name (e.g., “Credit Card” in Japanese) instead of the code identifier (e.g., CreditCard).

In such cases, the standard approach is to assign a [Display] attribute to each member and retrieve its value using Reflection.

目次

Implementing Attribute Retrieval for Enums

In the following sample code, we define Japanese names for each member of the PaymentMethod enum using the DisplayAttribute and then dynamically retrieve and display them.

Sample Code

using System;
using System.ComponentModel.DataAnnotations; // Required for DisplayAttribute
using System.Reflection;

public class Program
{
    public static void Main()
    {
        // Enum value to retrieve
        var selectedMethod = PaymentMethod.BankTransfer;

        Console.WriteLine($"Code Name: {selectedMethod}");

        // 1. Get Enum Type Info
        Type type = selectedMethod.GetType();

        // 2. Get FieldInfo corresponding to the value
        // EnumValue.ToString() returns the field name ("BankTransfer"), use it to search
        FieldInfo fieldInfo = type.GetField(selectedMethod.ToString());

        if (fieldInfo != null)
        {
            // 3. Get the DisplayAttribute assigned to the field
            // Using extension method from System.Reflection.CustomAttributeExtensions
            var attribute = fieldInfo.GetCustomAttribute<DisplayAttribute>();

            if (attribute != null)
            {
                // Display the Name property (Japanese name) of the attribute
                Console.WriteLine($"Display Name: {attribute.Name}");
            }
        }
    }
}

// Enum with attributes (Payment Method)
public enum PaymentMethod
{
    [Display(Name = "クレジットカード")] // Credit Card
    CreditCard,

    [Display(Name = "銀行振込")] // Bank Transfer
    BankTransfer,

    [Display(Name = "代金引換")] // Cash on Delivery
    CashOnDelivery,
    
    // Case without attribute
    Unknown
}

Execution Result

Code Name: BankTransfer
Display Name: 銀行振込

Explanation and Technical Points

1. Relationship between Enum and FieldInfo

Structurally, each member of an enumeration (like CreditCard) is defined as a static field of that Enum class. Therefore, to retrieve metadata, you must use the GetField method, not GetProperty.

2. Application to Generic Extension Methods

Since this process is used frequently, it is common to define it as an extension method like the one below, allowing it to be called simply as .ToDisplayName().

public static class EnumExtensions
{
    /// <summary>
    /// Gets the Name from the Enum's Display attribute. Returns ToString() if no attribute exists.
    /// </summary>
    public static string ToDisplayName(this Enum value)
    {
        if (value == null) return string.Empty;

        // Get Field Info
        var field = value.GetType().GetField(value.ToString());
        
        // Get Attribute
        var attribute = field?.GetCustomAttribute<DisplayAttribute>();

        // Return Name if attribute exists, otherwise return original string representation
        return attribute?.Name ?? value.ToString();
    }
}
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次