skip to content

In C#, what do [AttributeUsage]'s AttributeTargets, AllowMultiple and Inherited settings control, and what applies when an attribute class omits it?

level: middleimportance: should knowfreq 35%

answer

  1. an attribute on attributes
  2. where, how many, passed down
  3. the defaults are permissive
  4. field: on an auto-property

basics

~20 s

[AttributeUsage] declares where an attribute may be applied (AttributeTargets), whether it may repeat on one declaration (AllowMultiple) and whether reflection reports it on derived classes and overrides (Inherited). Without it: all targets, AllowMultiple false, Inherited true.

solid answer

~40 s

`[AttributeUsage]` is applied to an attribute class. Its positional `AttributeTargets` flags are enforced by the compiler: putting a method-only attribute on a property is CS0592. `AllowMultiple` (default `false`) decides whether the same attribute may appear twice on one declaration; a repeat otherwise is CS0579. `Inherited` (default `true`) is not a compile-time rule at all: it tells reflection, when called with `inherit: true`, to report a base class's or base method's attribute on the derived class or override. When both apply and `AllowMultiple` is `false`, the derived declaration's own instance hides the base one. Omitting `[AttributeUsage]` means `AttributeTargets.All`, `AllowMultiple = false`, `Inherited = true`. Target specifiers such as `field:`, `return:` and `assembly:` pick the exact element, for example the backing field of an auto-property.

code

csharp · 17 lines
csharp
using System.Reflection;

Console.WriteLine(string.Join(",", typeof(PaymentsHandler).GetCustomAttributes<OwnerAttribute>().Select(a => a.Team)));
Console.WriteLine(string.Join(",", typeof(PaymentsHandler).GetCustomAttributes<TagAttribute>().Select(a => a.Name)));
Console.WriteLine(typeof(PaymentsHandler).GetCustomAttribute<SampledAttribute>() is null);

[AttributeUsage(AttributeTargets.Class)]                       // AllowMultiple = false, Inherited = true
public sealed class OwnerAttribute(string team) : Attribute { public string Team { get; } = team; }

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class TagAttribute(string name) : Attribute { public string Name { get; } = name; }

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class SampledAttribute : Attribute { }

[Owner("platform"), Tag("base"), Sampled] public class HandlerBase { }
[Owner("payments"), Tag("payments")] public class PaymentsHandler : HandlerBase { }

go deeper

for a junior

Recall the three settings and that they sit on the attribute class itself: where it can go, whether it can repeat, whether it passes down.

for a middle

State the defaults (All, AllowMultiple false, Inherited true), the CS0592 and CS0579 errors, and how field:, return: and assembly: choose the element.

for a senior

Explain that Inherited is a reflection-time walk, not compiled metadata, that interfaces are not walked, and how AllowMultiple decides whether a derived instance hides the base one.

for a principal

Pick restrictive targets and explicit Inherited values for public library attributes so misuse fails the build instead of silently doing nothing for consumers.

## An attribute that describes attributes `System.AttributeUsageAttribute` is applied only to attribute classes (anywhere else the compiler reports **CS0641**, "Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute"). It has one positional argument and two named ones: ```csharp [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class TracedAttribute : Attribute { } ``` | Setting | Kind | Default when `[AttributeUsage]` is absent | Checked by | |---|---|---|---| | `ValidOn` (`AttributeTargets` flags) | positional | `AttributeTargets.All` | the compiler | | `AllowMultiple` | named | `false` | the compiler | | `Inherited` | named | `true` | reflection at run time | The defaults come straight from the runtime source: `AttributeUsageAttribute.Default` is built with `AttributeTargets.All`, the public constructor sets `Inherited` to `true`, and `AllowMultiple` starts as `false`. ## AttributeTargets: where it may appear `AttributeTargets` is a flags enum: `Assembly`, `Module`, `Class`, `Struct`, `Enum`, `Constructor`, `Method`, `Property`, `Field`, `Event`, `Interface`, `Parameter`, `Delegate`, `ReturnValue`, `GenericParameter` and the combination `All`. Combine values with `|`. Applying the attribute elsewhere is **CS0592**: "Attribute 'Traced' is not valid on this declaration type. It is only valid on 'method' declarations." This is the cheapest guard a library author has: misuse fails the build instead of being silently ignored by the reader. ## Target specifiers: which element gets it Some declarations produce more than one metadata element, so C# lets you name the target before a colon: - `[assembly: Owner("observability")]` and `[module: ...]` at file level, after the using directives. - `[return: Redact]` on a method puts the attribute on its return value, read back through `MethodInfo.ReturnParameter`. - `[field: Redact]` on an auto-implemented property puts it on the compiler-generated backing field; without the specifier the attribute goes on the property, and a field-only attribute there is CS0592. - `[param: ...]`, `[property: ...]` and `[field: ...]` on a positional record parameter choose among the parameter, the generated property and its field. - `[method: ...]` on a type with a primary constructor targets the constructor instead of the type. ## AllowMultiple: how many per declaration With `AllowMultiple = false`, writing `[Traced("a")] [Traced("b")]` on one method is **CS0579** ("Duplicate 'Traced' attribute"). Set it to `true` for list-like metadata such as tags, and read all instances with `GetCustomAttributes<T>()`; `GetCustomAttribute<T>()` throws `AmbiguousMatchException` when it finds more than one. ## Inherited: what reflection reports on derived members `Inherited` changes nothing in the compiled derived class. The metadata stays on the base declaration. It matters only when a reader asks reflection to walk the hierarchy with `inherit: true` (the default for `GetCustomAttribute<T>()` from `CustomAttributeExtensions`): 1. For a **class**, the walk goes up the base classes. 2. For an **overriding method**, the walk goes to the base method definitions. 3. Attributes on **interfaces** and interface members are never reported on the implementing class or method; the walk follows base classes only. 4. If `Inherited = false`, the walk skips the attribute even with `inherit: true`. 5. If the attribute appears on both levels and `AllowMultiple = false`, only the most derived instance is returned; with `AllowMultiple = true` both are returned, derived first. The built-in `[Obsolete]` and `[Experimental]` are declared `Inherited = false`, for example, so an override is not reported as obsolete through reflection just because its base is. ## Walking through the example The first snippet declares three class-level attributes and applies them to `HandlerBase` and `PaymentsHandler : HandlerBase`, then reads them on the derived class with the generic extension methods, which pass `inherit: true`: - `OwnerAttribute` keeps the defaults (`AllowMultiple = false`, `Inherited = true`). Both classes carry one, so the walk finds two, and because repetition is not allowed the derived class's `payments` instance hides the base's `platform`. The output is `payments`. - `TagAttribute` sets `AllowMultiple = true`, so the derived instance does not hide the inherited one; the output is `payments,base`, the derived class's own attribute first. - `SampledAttribute` sets `Inherited = false`. It sits only on the base class, and the walk skips it, so `GetCustomAttribute<SampledAttribute>()` on the derived class returns `null` and the line prints `True`. The second snippet shows the target specifier: `[field: Redact]` lands on `<Name>k__BackingField`, the compiler-generated field, and the property itself reports no attribute. ## Choosing settings for a library attribute - Restrict `AttributeTargets` to what your reader actually inspects; `All` invites uses nobody reads. - Leave `AllowMultiple` off unless repetition has a meaning, so a duplicate is an error rather than an ambiguity. - Set `Inherited = false` when the attribute describes one concrete declaration (an owner, a version stamp) rather than a contract subclasses share.

  • Does Inherited = true copy the attribute into the derived class's metadata?
    No. The compiler writes the attribute only on the declaration that carries it. `Inherited` is read by reflection when a caller passes `inherit: true` (or uses an overload that defaults to it), which then walks base classes or base method definitions. A tool that reads raw metadata of the derived class, without that walk, will not see it.
  • Why is an attribute on an interface method not found on the implementing method, even with inherit: true?
    The inheritance walk follows the base-class chain and overridden base methods only. Implementing an interface is not inheritance in that sense, so reflection does not report interface or interface-member attributes on the implementation. A reader that needs them maps the method with `Type.GetInterfaceMap` or reads the interface's members directly.

  • Believes Inherited makes the compiler copy the attribute onto derived classes
  • Thinks an attribute without AttributeUsage may be repeated on one declaration
  • Expects attributes on interface members to show up on implementing methods
  • Assumes a property attribute automatically lands on the auto-property's backing field
  • Thinks AttributeTargets violations are only detected when reflection reads the attribute