Codectionary / Developer documentation / C#

Custom Attributes and Reflection

Attributes attach metadata to program elements. Reflection can read that metadata at runtime; an attribute alone does not execute application behavior. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

Attributes attach metadata to program elements. Reflection can read that metadata at runtime; an attribute alone does not execute application behavior. Use a .NET 8+ console project; replace Program.cs with this C# example.

The annotation stores the constructor argument as metadata. The reflection call retrieves the attribute and reads its Text property.

Syntax

[AttributeUsage(AttributeTargets.Class)] class LabelAttribute : Attribute { ... }

Examples

Custom Attributes and Reflection

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
using System.Reflection;
var label = typeof(Report).GetCustomAttribute<LabelAttribute>();
Console.WriteLine(label?.Text ?? "unlabeled");

[AttributeUsage(AttributeTargets.Class)]
sealed class LabelAttribute : Attribute
{
    public string Text { get; }
    public LabelAttribute(string text) => Text = text;
}
[Label("Monthly report")]
sealed class Report { }
  1. Expected output: Monthly report
  2. The annotation stores the constructor argument as metadata. The reflection call retrieves the attribute and reads its Text property.
  3. Restrict AttributeUsage to the program elements where the metadata makes sense.

Best practices

  • Restrict AttributeUsage to the program elements where the metadata makes sense.
  • Account for trimming and AOT requirements when designing reflection-heavy code.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading