[C#] Retrieving Attribute Values Assigned to Properties (GetCustomAttribute)

There are cases where you not only need to confirm the existence of an attribute assigned to a specific property but also want to read the specific values set on that attribute (e.g., label names for screen display, error messages, configuration values).

By using C# Reflection and the GetCustomAttribute<T> extension method, you can retrieve the instance of the attribute object itself and access its property values.

目次

Implementation of Retrieving Attribute Values

The following sample code implements a process that extracts the Japanese display name from the [Display(Name="...")] attribute assigned to properties of a Product class and outputs it to the console.

Sample Code

using System;
using System.ComponentModel.DataAnnotations; // For DisplayAttribute
using System.Reflection;

public class Program
{
    public static void Main()
    {
        // 1. Get target type information
        Type type = typeof(Product);

        Console.WriteLine("--- Attribute Value Retrieval Results ---");

        // 2. Get and display DisplayAttribute values for each property
        // Using the nameof operator makes the code resilient to property name changes
        PrintDisplayName(type, nameof(Product.ProductName));
        PrintDisplayName(type, nameof(Product.UnitPrice));
        
        // (Ref) Case for a property without the attribute
        PrintDisplayName(type, nameof(Product.StockCount));
    }

    /// <summary>
    /// Outputs the Name value of the DisplayAttribute for the specified property
    /// </summary>
    static void PrintDisplayName(Type type, string propertyName)
    {
        // Get property info
        PropertyInfo prop = type.GetProperty(propertyName);
        
        if (prop == null) return;

        // 3. Get attribute instance
        // GetCustomAttribute<T>() returns the instance if the specified attribute is found,
        // otherwise it returns null.
        var attr = prop.GetCustomAttribute<DisplayAttribute>();

        if (attr != null)
        {
            // Access the attribute's property (Name)
            Console.WriteLine($"Property: {propertyName,-12} | Display Name: {attr.Name}");
        }
        else
        {
            Console.WriteLine($"Property: {propertyName,-12} | No Attribute");
        }
    }
}

// Data Class
public class Product
{
    // Define name for screen display using attribute
    [Display(Name = "Product Name")]
    public string ProductName { get; set; }

    [Display(Name = "Unit Price")]
    public int UnitPrice { get; set; }
    
    // Property without attribute
    public int StockCount { get; set; }
}

Execution Result

--- Attribute Value Retrieval Results ---
Property: ProductName  | Display Name: Product Name
Property: UnitPrice    | Display Name: Unit Price
Property: StockCount   | No Attribute

Explanation and Technical Points

1. GetCustomAttribute<T> Method

This method is an extension method included in the System.Reflection.CustomAttributeExtensions class. You call it by specifying the type of attribute you want to retrieve (in this case, DisplayAttribute) in the generic type argument T. Since it returns an instance of the attribute class, you can access its properties (such as attr.Name) using the dot operator, just like a normal class.

2. Utilizing the nameof Operator

While it is possible to write the property name directly as a string literal "ProductName", using nameof(Product.ProductName) prevents errors when refactoring (renaming) and allows spelling mistakes to be detected at compile time.

3. About DisplayAttribute

This is a standard attribute located in the System.ComponentModel.DataAnnotations namespace. Frameworks such as ASP.NET Core MVC and Entity Framework have built-in mechanisms to automatically read this attribute value and use it as an input form label or validation message. The code above demonstrates how to implement this “reading process” yourself.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次