[C#] How to Get Attributes Attached to a Class

You can use the GetCustomAttributes method of the Type class to retrieve metadata attached to a class definition (such as author information, version, deprecation warnings, or database table names) at runtime.

This allows you to search for and load only classes with specific attributes, or change the program’s behavior based on the settings written in the attributes.

目次

Table of Contents

  • Implementation of Class Attribute Retrieval
  • Sample Code
  • Execution Result
  • Explanation and Technical Points
    1. GetCustomAttributes Method
    2. AttributeUsage Attribute
    3. Practical Examples

Implementation of Class Attribute Retrieval

In the following sample code, I define a custom attribute called DeveloperInfoAttribute to record developer information. I then implement the logic to read this information from a class that has this attribute.

I also retrieve the standard ObsoleteAttribute (used for deprecated items) to show how to handle built-in attributes.

Sample Code

using System;
using System.Reflection;

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

        Console.WriteLine($"Attributes list for class '{type.Name}':\n");

        // 2. Get all custom attributes attached to the class
        // If inherit: true, it searches parent class attributes too
        object[] attributes = type.GetCustomAttributes(inherit: false);

        foreach (var attr in attributes)
        {
            // Process based on attribute type
            if (attr is DeveloperInfoAttribute devAttr)
            {
                Console.WriteLine($"[Developer Info] Name: {devAttr.DeveloperName}, Date: {devAttr.Date}");
            }
            else if (attr is ObsoleteAttribute obsAttr)
            {
                Console.WriteLine($"[Deprecation Warning] Message: {obsAttr.Message}");
            }
            else
            {
                // Other attributes
                Console.WriteLine($"[Other] {attr.GetType().Name}");
            }
        }
    }
}

// ---------------------------------------------------------
// Definition of custom attribute
// Use AttributeUsage to specify that this is only valid for classes
// ---------------------------------------------------------
[AttributeUsage(AttributeTargets.Class)]
public class DeveloperInfoAttribute : Attribute
{
    public string DeveloperName { get; }
    public string Date { get; }

    public DeveloperInfoAttribute(string developerName, string date)
    {
        DeveloperName = developerName;
        Date = date;
    }
}

// ---------------------------------------------------------
// Class with attributes attached
// ---------------------------------------------------------
[DeveloperInfo("Taro Yamada", "2023-12-01")]
[Obsolete("This class is planned for removal. Please use NewDataProcessor.")]
[Serializable] // Adding a standard attribute too
public class OldDataProcessor
{
    public void Process()
    {
        Console.WriteLine("Processing...");
    }
}

Execution Result

Attributes list for class 'OldDataProcessor':

[Developer Info] Name: Taro Yamada, Date: 2023-12-01
[Deprecation Warning] Message: This class is planned for removal. Please use NewDataProcessor.
[Other] SerializableAttribute

Explanation and Technical Points

1. GetCustomAttributes Method

This is a method of the Type class (which inherits from MemberInfo). It returns all attribute instances applied to that type as an object[] array.

If you only want to retrieve specific attributes, it is often more convenient to use the generic versions:

  • GetCustomAttribute<T>(): Retrieves a single attribute.
  • GetCustomAttributes<T>(): Retrieves multiple attributes.

2. AttributeUsage Attribute

When creating your own attribute class (like DeveloperInfoAttribute in the example), use [AttributeUsage] to control “where” the attribute can be attached (e.g., classes, methods, properties).

  • AttributeTargets.Class: Allows the attribute to be placed on classes.
  • AllowMultiple: Specifies whether the same attribute can be attached multiple times to the same target.

3. Practical Examples

This technique is widely used in many common scenarios:

  • Plugin Systems: Finding and loading classes from a DLL that have a specific attribute (e.g., [Plugin("Name")]).
  • Unit Tests: Test runners recognize classes marked with [TestClass] or [TestFixture].
  • O/R Mappers: Reading attributes like [Table("TableName")] to map classes to database tables.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次