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 { }- Expected output: Monthly report
- The annotation stores the constructor argument as metadata. The reflection call retrieves the attribute and reads its Text property.
- 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