Custom Attributes, `AttributeUsage` & Runtime Metadata Extraction
1Concept
Custom attributes inherit from `System.Attribute` and embed serialized metadata blobs into assembly tables. `AttributeUsage` restricts target targets (Class, Method, Property) and controls inheritance.
2Architecture Diagram
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EndpointRouteAttribute : Attribute
│
▼
Decorates Class / Method ──> Extracted via `member.GetCustomAttribute<T>()` 3Code Example
C# 13 & .NET 9
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class HttpPostAttribute(string route) : Attribute
{
public string Route { get; } = route;
}
public class OrderController
{
[HttpPost("/api/orders/checkout")]
public void Checkout() => Console.WriteLine("Processing checkout...");
}
public class CustomAttributeDemo
{
public static void Main()
{
var method = typeof(OrderController).GetMethod("Checkout");
var attr = method?.GetCustomAttribute<HttpPostAttribute>();
Console.WriteLine($"Discovered Endpoint Route: {attr?.Route}");
}
}4Expected Output
Discovered Endpoint Route: /api/orders/checkout
5Key Takeaways
- ✓Always seal custom attributes to enable compiler optimizations.
- ✓Set `Inherited = false` when attribute behavior should not cascade to derived subclasses.
- ✓Use attributes for declarative framework design (validation, routing, authorization).