Glossary / Attributes

Attributes

Attributes attach declarative metadata to assemblies, types, members, parameters, and other program elements. They are instances of attribute classes encoded in assembly metadata and can be inspected by compilers, analyzers, frameworks, serializers, test runners, and reflection-based tooling.

Declaration and consumption

[Obsolete("Use NewApi instead", error: false)]
public void OldApi() { }

An attribute class derives from System.Attribute; positional and named arguments are restricted to compile-time constants and supported attribute parameter types. Attribute usage can be constrained with AttributeUsage, including valid targets, multiplicity, and inheritance behavior. Applying an attribute does not execute arbitrary code at compile time; a consumer decides whether to interpret it.

Attributes can influence compiler diagnostics (Obsolete, nullability flow annotations), runtime frameworks (serialization, dependency injection), or build tooling. Reflection retrieval may instantiate attributes; CustomAttributeData can inspect metadata without constructing them. Attribute names and constructor signatures can become API contracts.

Engineering guidance

Prefer attributes for declarative metadata, not hidden control flow. Document whether behavior is compiler-, build-, or runtime-consumed. Avoid expensive reflection scans and trim/AOT-incompatible patterns without explicit preservation. Version attribute contracts carefully and validate the consumer that reads them.

Interview questions

  1. What is an attribute? Metadata attached to program elements and encoded in assemblies.
  2. Does applying an attribute run its class constructor at compile time? No; consumers may instantiate/read it later.
  3. What can attribute arguments be? Restricted constant and supported type forms.
  4. How inspect without instantiate? CustomAttributeData.
  5. Why can attributes affect trimming? Reflection-driven use may hide dependencies from static analysis unless preserved/annotated.

References