Attributes: The Sticky Labels

Attributes: The Sticky Labels in C#: A crate in a warehouse carries labels that the crate itself does not act on. FRAGILE. THIS WAY UP. DO NOT STACK ABOVE 3.

The Analogy: FRAGILE, THIS WAY UP

A crate in a warehouse carries labels that the crate itself does not act on. FRAGILE. THIS WAY UP. DO NOT STACK ABOVE 3. The cardboard is indifferent to all of it; the labels exist for the forklift driver, the loading algorithm and the insurance auditor. Peel them off and the crate is unchanged — but everything downstream now treats it as an ordinary box.

An attribute is a sticky label on a piece of code. [Obsolete] on a method does not stop it running. [Required] on a property does not validate anything. [JsonPropertyName("price_usd")] does not rename anything by itself. Each one writes a fact into the assembly's metadata and waits for a reader: the compiler, a serializer, a test runner, a dependency injection container, or a validator you wrote yourself.

That split — the label and its reader — is the thing to hold on to. Half of learning attributes is knowing which labels have a reader already built in (a great many, and the compiler is the most important one), and the other half is learning to write your own labels and the code that acts on them.


Syntax or Core Structure

An attribute is an ordinary class inheriting Attribute. Applying it is square brackets; reading it back is reflection.

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
class AuditedAttribute : Attribute
{
    public string Reason { get; }                       // positional: constructor arg
    public string Owner { get; set; } = "unassigned";   // named: settable property

    public AuditedAttribute(string reason) => Reason = reason;
}

// The "Attribute" suffix is dropped at the point of use.
[Audited("handles money", Owner = "payments")]
class Payment
{
    [Obsolete("Use Settle instead.")]
    public void Pay() => Console.WriteLine("paying");

    public void Settle() => Console.WriteLine("settling");
}

class Program
{
    static void Main()
    {
        // The label does nothing until something reads it.
        AuditedAttribute? label = typeof(Payment).GetCustomAttribute<AuditedAttribute>();
        Console.WriteLine(label is null ? "no label" : label.Reason + " / " + label.Owner);

        MethodInfo pay = typeof(Payment).GetMethod("Pay")!;
        ObsoleteAttribute? old = pay.GetCustomAttribute<ObsoleteAttribute>();
        Console.WriteLine("Pay obsolete: " + (old is not null) + " -> " + old!.Message);

        MethodInfo settle = typeof(Payment).GetMethod("Settle")!;
        Console.WriteLine("Settle obsolete: " + (settle.GetCustomAttribute<ObsoleteAttribute>() is not null));
    }
}

Output:

handles money / payments
Pay obsolete: True -> Use Settle instead.
Settle obsolete: False

Two syntaxes appear in that one application: "handles money" is positional, matched to a constructor parameter, and Owner = "payments" is named, assigned to a public settable property after construction. Named arguments must follow all positional ones, and both are how the framework's own attributes are shaped — [Obsolete("message", error: true)] is exactly the same idea.


Technical Depth: Metadata, Not Code

Everything must be known at compile time

An attribute application is baked into the assembly as a blob of constants, which is why the arguments are so restricted:

[Audited("handles money")]                  // string constant: fine
[Audited(nameof(Payment))]                  // nameof is a constant: fine
[Cache(typeof(Order))]                      // typeof: fine
[Roles(new[] { "admin", "auditor" })]       // array of constants: fine

// [Audited(DateTime.Now.ToString())]       // ERROR: not a compile-time constant
// [Cache(new Order())]                     // ERROR: no object creation

Permitted values are primitives, string, enum, Type via typeof, and single-dimension arrays of those. The instance you get back from GetCustomAttribute is constructed at that moment, fresh, from the stored blob — so an attribute has no lifetime and no state to share, and two reads give you two objects.

AttributeUsage: the label's own label

SettingMeansDefault
TargetsWhere it may be applied — class, method, property, parameter, assemblyAll
AllowMultipleWhether it can appear twice on the same targetfalse
InheritedWhether a derived class or override reports it tootrue

Inherited = true only affects GetCustomAttribute calls that pass inherit: true — the generic overload does by default, so a base class's [Audited] shows up on subclasses unless you opt out. Setting Targets precisely turns misuse into a compile error rather than a silently ignored label.

Target specifiers, and the record trap

When a declaration expands into several members, an attribute needs to be told which one it belongs to:

[assembly: InternalsVisibleTo("MyApp.Tests")]   // whole assembly
[return: NotNull]                                // the return value
[field: NonSerialized]                           // the backing field, not the property

// A positional record's parameters are parameters first, properties second.
record Product([property: JsonPropertyName("price_usd")] decimal Price);

That last one catches everyone. Without property:, the attribute lands on the constructor parameter, where the serializer never looks, and the JSON name is silently ignored.

The labels the compiler reads itself

These are not documentation. Each one changes what is compiled or what is diagnosed:

AttributeWhat it actually does
[Obsolete("...", error: true)]Warning, or a hard compile error, at every call site
[Conditional("DEBUG")]Call sites are removed unless the symbol is defined
[CallerMemberName], [CallerLineNumber], [CallerArgumentExpression]Arguments filled in by the compiler at each call
[Flags]Changes an enum's ToString to a comma-separated list
[MethodImpl(MethodImplOptions.AggressiveInlining)]Instructs the JIT about inlining
[StructLayout], [LibraryImport]Field layout and native interop signatures
[NotNullWhen(true)], [MemberNotNull]Teaches nullable flow analysis about your Try methods
[DebuggerDisplay], [DebuggerStepThrough]How the debugger shows and steps your type

[Conditional] is the surprising one — the method still exists, but every call to it vanishes from a release build, arguments and all, which is how Debug.Assert costs nothing in production.

Reading labels cheaply, or not at all

GetCustomAttribute walks metadata, allocates, and is far too slow for a hot path. Reflection-based frameworks all do the same thing: read once per type, cache the result.

static readonly Dictionary<Type, RuleSet> Cache = new();

static RuleSet RulesFor(Type type)
{
    if (!Cache.TryGetValue(type, out RuleSet? rules))
        Cache[type] = rules = BuildFromAttributes(type);   // reflection once
    return rules;
}

The modern alternative skips run time entirely. A source generator reads your attributes during compilation and emits ordinary code — [GeneratedRegex], [LoggerMessage] and [JsonSerializable] all work this way. No reflection, no startup cost, and it survives trimming and Native AOT, where reflecting over types the trimmer removed fails outright.

Attribute or interface?

A marker attribute and a marker interface solve the same problem differently. class Order : IAuditable is checked at compile time and tested with a cheap is — but it changes the type's public contract and cannot carry data. [Audited("handles money", Owner = "payments")] carries as much data as you like and leaves the type's contract alone, at the cost of a reflection read. Data and optionality point to an attribute; behaviour and compile-time enforcement point to an interface.


Real World Example: A Validator Driven by Labels

Validation rules written as if statements drift away from the model they guard. Written as labels, the rule sits on the property it constrains, and one small engine enforces every one of them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

[AttributeUsage(AttributeTargets.Property)]
class RequiredAttribute : Attribute { }

[AttributeUsage(AttributeTargets.Property)]
class MaxLengthAttribute : Attribute
{
    public int Length { get; }
    public MaxLengthAttribute(int length) => Length = length;
}

[AttributeUsage(AttributeTargets.Property)]
class LabelAttribute : Attribute
{
    public string Text { get; }
    public LabelAttribute(string text) => Text = text;
}

class SignUpForm
{
    [Required, Label("Full name")]
    [MaxLength(20)]
    public string? Name { get; set; }

    [Required, Label("Email address")]
    public string? Email { get; set; }

    [MaxLength(5)]
    public string? Postcode { get; set; }
}

static class Validator
{
    public static List<string> Validate(object target)
    {
        var errors = new List<string>();

        // GetProperties order is unspecified, so state one.
        foreach (PropertyInfo property in target.GetType().GetProperties().OrderBy(p => p.Name))
        {
            string label = property.GetCustomAttribute<LabelAttribute>()?.Text ?? property.Name;
            string? value = property.GetValue(target) as string;

            if (property.GetCustomAttribute<RequiredAttribute>() is not null
                && string.IsNullOrWhiteSpace(value))
                errors.Add(label + " is required");

            MaxLengthAttribute? max = property.GetCustomAttribute<MaxLengthAttribute>();
            if (max is not null && value is not null && value.Length > max.Length)
                errors.Add(label + " must be " + max.Length + " characters or fewer");
        }

        return errors;
    }
}

class Program
{
    static void Main()
    {
        var good = new SignUpForm { Name = "Ada Lovelace", Email = "ada@example.com", Postcode = "LS1" };
        var bad = new SignUpForm { Name = "A very long name indeed", Email = "  ", Postcode = "LS1 4AP" };

        Report("good", Validator.Validate(good));
        Report("bad", Validator.Validate(bad));

        // The same labels are useful for rendering, not just checking.
        foreach (PropertyInfo p in typeof(SignUpForm).GetProperties().OrderBy(p => p.Name))
            Console.WriteLine(p.Name + " -> " + (p.GetCustomAttribute<LabelAttribute>()?.Text ?? "(no label)"));
    }

    static void Report(string name, List<string> errors)
    {
        Console.WriteLine(name + ": " + (errors.Count == 0 ? "ok" : errors.Count + " problem(s)"));
        foreach (string e in errors) Console.WriteLine("  - " + e);
    }
}

Output:

good: ok
bad: 3 problem(s)
  - Email address is required
  - Full name must be 20 characters or fewer
  - Postcode must be 5 characters or fewer
Email -> Email address
Name -> Full name
Postcode -> (no label)

Validator has never heard of SignUpForm. Add a property with [Required] tomorrow and it is enforced with no change here — that is the payoff, and it is why System.ComponentModel.DataAnnotations, ASP.NET Core model binding and every ORM's mapping layer are built exactly this way.

Three details in that output are worth naming. Postcode has no [Label], so the engine fell back to the property name — an attribute is absent far more often than it is wrong, and ?. plus ?? is the whole story for handling that. The message for Name reads 20 because the attribute carried data, not just a marker. And the report is alphabetical because GetProperties makes no promise about order: relying on declaration order works until someone reorders the class or adds a partial file, at which point your error list quietly rearranges itself.

The engine as written also reflects on every call, which is fine for one form submission and wrong for a hot path. Cache a rule list per Type in a static dictionary and the reflection happens once per process.


Common Mistakes

  1. Expecting the label to act. [Required] with no engine reading it validates nothing. An attribute without a reader is a comment with brackets.
  2. Forgetting [AttributeUsage]. The default allows your label on anything, so a property-only rule can be stuck on a class or a parameter and silently ignored.
  3. Omitting the target specifier on a record. record Product([JsonPropertyName("p")] decimal Price) labels the constructor parameter; serializers look at the property. Write [property: ...].
  4. Trying to pass runtime values. [Audited(DateTime.Now.ToString())] will not compile. Only compile-time constants, typeof, enums and arrays of those are allowed.
  5. Storing state in an attribute instance. Every GetCustomAttribute call builds a new object, so a counter or cache field inside one is always freshly zero.
  6. Reflecting on every call. GetCustomAttribute in a per-request loop is a measurable cost. Read once per type and cache.
  7. Overlooking inheritance. Inherited defaults to true, so a base class's marker appears on every subclass — occasionally exactly wrong, and always worth deciding deliberately.
  8. Assuming reflection survives trimming. A trimmed or Native AOT build may have removed the very members you reflect over. Prefer source-generator-backed attributes there.

Best Practices

  • Name the class with the Attribute suffix, apply it without — class AuditedAttribute, used as [Audited].
  • Declare [AttributeUsage] on every custom attribute, with the narrowest Targets that make sense and an explicit AllowMultiple.
  • Make required data a constructor parameter and optional data a settable property, so misuse is a compile error rather than a default nobody chose.
  • Keep attributes as pure data. Put the behaviour in the reader, where it can be tested without reflection.
  • Cache reflection results per Type in a static dictionary — every serious attribute-driven framework does.
  • Prefer a source generator over runtime reflection when the label's meaning is fixed at compile time; it is faster, trimming-safe and diagnosable in the IDE.
  • Reach for [Obsolete] with a message that names the replacement, and escalate to error: true once the migration window closes.
  • Choose an interface when you need compile-time enforcement or behaviour, and an attribute when you need optional data that does not belong in the type's contract.

Practice Exercises

  1. Write a [Description] attribute for enum members, then a helper that takes any enum value and returns its description, falling back to ToString() when the label is missing.
  2. Add a [Range(int min, int max)] attribute to the validator above, make it work for int properties, and extend SignUpForm with an Age property to prove it.
  3. Add a per-Type cache to Validator so reflection runs once, then time 100,000 validations with and without the cache using a Stopwatch.
  4. Write a method static void Trace(string message, [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0) and call it from two different methods to show the compiler filling both arguments in.