CustomAttributeBuilder Class

Namespace: System.Reflection.Emit
Base Type: Object

Represents a custom attribute, enabling you to build and associate custom attributes with dynamic types, methods, and members at runtime. This class is part of the Reflection.Emit API, allowing for advanced meta-programming scenarios.

Constructors

Methods

Remarks

The CustomAttributeBuilder class is a crucial component for dynamically creating custom attributes in .NET. It allows you to define the structure and values of an attribute at runtime, which can then be applied to dynamically generated types, methods, or other members. This is particularly useful in scenarios like:

When creating a CustomAttributeBuilder, you typically provide:

The resulting CustomAttributeBuilder can then be passed to methods on TypeBuilder, MethodBuilder, or other relevant emission classes to associate the custom attribute with the generated code element.

Example


using System;
using System.Reflection;
using System.Reflection.Emit;

public class DynamicAttributeUsage
{
    public static void Main(string[] args)
    {
        // Define a simple custom attribute for demonstration
        // This would typically be a pre-defined attribute class
        // For this example, we'll simulate it by using an existing type with attributes

        // Create an in-memory assembly and module
        AssemblyName assemblyName = new AssemblyName("MyDynamicAssembly");
        AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");

        // Define a dynamic type
        TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType");

        // Get the constructor of the AttributeUsage attribute
        ConstructorInfo attributeUsageConstructor = typeof(System.AttributeUsageAttribute).GetConstructor(new Type[] { typeof(AttributeTargets) });

        // Create arguments for the AttributeUsage constructor
        object[] attributeUsageArgs = { AttributeTargets.Class | AttributeTargets.Method };

        // Create a CustomAttributeBuilder for AttributeUsage
        CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(
            attributeUsageConstructor,
            attributeUsageArgs);

        // Apply the custom attribute to the dynamic type
        typeBuilder.SetCustomAttribute(attributeBuilder);

        // Create a dynamic method
        MethodBuilder methodBuilder = typeBuilder.DefineMethod(
            "MyDynamicMethod",
            MethodAttributes.Public | MethodAttributes.Static,
            typeof(void),
            null);

        // Get the constructor of the Obsolete attribute
        ConstructorInfo obsoleteConstructor = typeof(System.ObsoleteAttribute).GetConstructor(new Type[] { typeof(string) });

        // Create arguments for the Obsolete constructor
        object[] obsoleteArgs = { "This method is obsolete." };

        // Create a CustomAttributeBuilder for Obsolete
        CustomAttributeBuilder obsoleteAttributeBuilder = new CustomAttributeBuilder(
            obsoleteConstructor,
            obsoleteArgs);

        // Apply the custom attribute to the dynamic method
        methodBuilder.SetCustomAttribute(obsoleteAttributeBuilder);

        // Create the type
        Type dynamicType = typeBuilder.CreateType();

        Console.WriteLine($"Dynamic type '{dynamicType.Name}' created with AttributeUsage applied.");
        MethodInfo dynamicMethod = dynamicType.GetMethod("MyDynamicMethod");
        Console.WriteLine($"Dynamic method '{dynamicMethod.Name}' created with Obsolete attribute applied.");

        // You can further inspect attributes using reflection
        var attrs = dynamicType.GetCustomAttributes(typeof(System.AttributeUsageAttribute), false);
        if (attrs.Length > 0)
        {
            var usageAttr = (System.AttributeUsageAttribute)attrs[0];
            Console.WriteLine($"AttributeUsage on {dynamicType.Name}: Targets = {usageAttr.ValidOn}");
        }

        var methodAttrs = dynamicMethod.GetCustomAttributes(typeof(System.ObsoleteAttribute), false);
        if (methodAttrs.Length > 0)
        {
            var obsoleteAttr = (System.ObsoleteAttribute)methodAttrs[0];
            Console.WriteLine($"Obsolete on {dynamicMethod.Name}: Message = '{obsoleteAttr.Message}'");
        }
    }
}

Inheritance

Object
    ↳ CustomAttributeBuilder