skip to content

Custom Attributes

Attributes attach metadata read by reflection or the compiler, from [Obsolete] and [Conditional] to caller info such as [CallerMemberName]. Interviewers ask how to write and read one.

on this pageshow

explore

questions

6

In C#, how do you declare a custom attribute such as [Traced("checkout")], and which argument types can its constructor and properties take?

level: juniorimportance: must knowfreq 55%

answer

  1. derive from one base class
  2. constructor vs settable property
  3. values baked into metadata
  4. constants, typeof, arrays only

basics

~20 s

Declare a class deriving from System.Attribute, conventionally named with the Attribute suffix. Constructor parameters become positional arguments and public read-write properties or fields become named ones; every argument must be a constant, a typeof expression or an array of those.

solid answer

~40 s

A custom attribute is a class that derives from `System.Attribute`, conventionally named `TracedAttribute` and applied as `[Traced(...)]`. Public constructor parameters are the **positional** arguments, and public read-write properties or fields are the **named** arguments, as in `[Traced("checkout", SampleEvery = 10)]`. The compiler stores the argument values in metadata, so they must be compile-time constants, `typeof` expressions or one-dimensional arrays of an attribute parameter type: the simple types such as `int` and `string`, `object`, `Type` or an enum. A non-constant argument is CS0182, and a `decimal` or `DateTime` parameter is CS0181. Since C# 11 an attribute class can also be generic, as in `[Redactor<CardNumberRedactor>]`. The attribute object itself is only created when reflection reads it.

code

csharp · 25 lines
csharp
using System.Reflection;

var method = typeof(CheckoutService).GetMethod(nameof(CheckoutService.PlaceOrder))!;
var traced = method.GetCustomAttribute<TracedAttribute>()!;
Console.WriteLine($"{traced.Operation}, sample 1 in {traced.SampleEvery}, tags: {string.Join("|", traced.Tags)}");
Console.WriteLine(method.GetCustomAttribute<RedactorAttribute<CardNumberRedactor>>() is not null);

[AttributeUsage(AttributeTargets.Method)]
public sealed class TracedAttribute(string operation) : Attribute
{
    public string Operation { get; } = operation;   // positional: constructor parameter
    public int SampleEvery { get; set; } = 1;       // named: public read-write property
    public string[] Tags { get; set; } = [];
}

[AttributeUsage(AttributeTargets.Method)]
public sealed class RedactorAttribute<TRedactor> : Attribute where TRedactor : new() { }
public sealed class CardNumberRedactor { }

public class CheckoutService
{
    [Traced("checkout.place-order", SampleEvery = 10, Tags = ["payments", "orders"])]
    [Redactor<CardNumberRedactor>]
    public void PlaceOrder() { }
}

go deeper

for a junior

Know that an attribute is a class deriving from System.Attribute, that the Attribute suffix is optional at the use site, and the difference between positional and named arguments.

for a middle

Explain why arguments must be constants, typeof or arrays, list the allowed parameter types, and name CS0182 and CS0181 when a decimal or a static field sneaks in.

for a senior

Point out that each reflective read constructs a new instance, keep constructors free of side effects, and know when a generic attribute's compile-time constraint beats a Type argument.

for a principal

Treat an attribute as a public contract of a library: its argument shapes are hard to change later, so pick constructor-required versus optional named settings deliberately.

## What an attribute class is An **attribute** in C# is declarative metadata attached to a declaration: a type, a method, a property, a parameter, a return value or the assembly itself. The compiler writes it into the assembly's metadata tables, and something else (reflection at run time, the compiler itself, an analyzer or a source generator) decides what it means. On its own an attribute does nothing. A **custom attribute** is an ordinary class with one requirement: it derives, directly or indirectly, from `System.Attribute`. By convention its name ends in `Attribute`, and the compiler lets you drop the suffix when you apply it, so `TracedAttribute` is written `[Traced]`. Most attribute classes also carry `[AttributeUsage]` to say where they may appear; that attribute has its own rules for targets, repetition and inheritance. ```csharp [AttributeUsage(AttributeTargets.Method)] public sealed class TracedAttribute(string operation) : Attribute { public string Operation { get; } = operation; // positional public int SampleEvery { get; set; } = 1; // named } ``` ## Positional and named arguments An application such as `[Traced("checkout.place-order", SampleEvery = 10)]` has two kinds of argument: - **Positional arguments** match a public constructor's parameters, in order. They are mandatory unless the constructor overloads or default values say otherwise. - **Named arguments** are written `Name = value` after the positional ones. Each must name a public, non-static, read-write field or property of the attribute class; the value is assigned after the constructor runs. A common design rule follows from that split: put what every use must supply in the constructor (the operation name), and make the optional knobs (sampling, tags) settable properties with sensible defaults. ## What the compiler accepts as an argument Because the values are serialized into metadata, the C# compiler restricts both the **parameter types** and the **argument expressions**. | Allowed attribute parameter types | Not allowed | |---|---| | `bool`, `byte`, `sbyte`, `char`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `float`, `double`, `string` | `decimal` | | `object` (holding one of the allowed values) | `DateTime`, `Guid`, `TimeSpan` | | `System.Type` | any other class or struct | | enum types | `dynamic` | | one-dimensional arrays of the above | multi-dimensional arrays | The diagnostics you meet, with the text the SDK 10.0.401 compiler printed: 1. **CS0182**, "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type", when you pass a `static` field, a method call or `new Something()`. 2. **CS0181**, when a constructor parameter has an invalid type such as `decimal`; it is reported where the attribute is applied. 3. **CS0655**, when a named argument targets a property whose type is not a valid attribute parameter type. `const` fields, `nameof(...)`, string concatenation of constants and enum values are all constant expressions, so they work. A collection expression such as `Tags = ["payments", "orders"]` also compiles to an array creation for a `string[]` property. ## Generic attributes (C# 11) Before C# 11 an attribute that names a type took a `Type` argument: `[Redactor(typeof(CardNumberRedactor))]`. Since C# 11 the class itself may be generic, `class RedactorAttribute<TRedactor> : Attribute`, applied as `[Redactor<CardNumberRedactor>]`. The type argument is checked by the compiler, so a `where TRedactor : new()` constraint is enforced at the declaration that uses it. Two limits apply: - The type argument must be fully known: `[Redactor<T>]` inside a generic class is **CS8968** ("an attribute type argument cannot use type parameters"). - Types the metadata cannot represent as a type argument, such as `dynamic`, are rejected, the same restrictions `typeof` has. ## When the attribute object exists Applying `[Traced(...)]` does not create a `TracedAttribute` object at startup. The compiler records the constructor and the argument values as a metadata blob. Only when code calls `GetCustomAttribute<TracedAttribute>()` or a similar reflection method does the runtime run the constructor and the property setters, and it builds a **new instance on every such call**. Two consequences: - Constructor side effects (logging, validation) run at read time, possibly many times, so attribute constructors should only store values. - A hot path that reads attributes should cache what it reads. ## Conventions worth following - Seal the class; the code-analysis rule CA1813 ("Avoid unsealed attributes") flags unsealed ones because lookups must consider derived types. - Expose positional values as get-only properties so readers can see them. - Keep the class free of behaviour: the attribute describes, and the code that reads it acts.

  • Why does a decimal price parameter on an attribute constructor fail, and what do you use instead?
    Attribute arguments are serialized into metadata, and `decimal` is not one of the attribute parameter types, so applying the attribute reports CS0181. Use `double` if precision allows, a `string` parsed with an invariant culture by the code that reads the attribute, or an `int` in minor units such as cents. The same rule rules out `DateTime` and `Guid`; pass them as strings and parse them at read time.
  • When does the constructor of a custom attribute actually run?
    Not when the assembly loads and not when the attributed method runs. The runtime runs the constructor and the named-argument setters each time reflection materializes the attribute, for example through `GetCustomAttribute<T>()`, and each call produces a new instance. `IsDefined` and `GetCustomAttributesData` can inspect an attribute without running its constructor.
  • What does a generic attribute such as [Redactor<CardNumberRedactor>] give you over [Redactor(typeof(CardNumberRedactor))]?
    With the generic form, available since C# 11, the compiler checks the type argument against the attribute's constraints, such as `where TRedactor : new()`, so a wrong type fails the build instead of failing when the reader calls `Activator`. Readers also get the type from the attribute's generic argument rather than a `Type` property. It cannot use an enclosing type parameter (CS8968).

  • Thinks applying an attribute changes the behaviour of the method by itself
  • Believes any expression, such as DateTime.Now or a static field, can be an attribute argument
  • Thinks named attribute arguments map to optional constructor parameters
  • Says the attribute instance is created once when the assembly loads
  • Believes decimal and DateTime are valid attribute parameter types
open as a page

In .NET, how do you read a custom [Traced] attribute at run time, and what do GetCustomAttribute<T>, IsDefined and the inherit argument do?

level: middleimportance: must knowfreq 45%

basics

~10 s

Get the MemberInfo, then call GetCustomAttribute<TracedAttribute>() for one instance (null if absent, AmbiguousMatchException if several), GetCustomAttributes<T>() for all, or IsDefined for a presence check. inherit: true also searches base classes and overridden members.

open as a page

In C#, how do [CallerMemberName] and the other caller-info attributes let OnPropertyChanged or a trace helper work without string literals?

level: juniorimportance: should knowfreq 40%

basics

~10 s

Caller-info attributes mark optional parameters that the compiler fills at each call site: [CallerMemberName] with the calling member's name, [CallerFilePath] and [CallerLineNumber] with its location, and [CallerArgumentExpression] with another argument's source text.

open as a page

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%

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.

open as a page

In C#, what does [Conditional("DEBUG")] on a logging method remove from a Release build, and whose build symbols decide it?

level: middleimportance: should knowfreq 30%

basics

~20 s

[Conditional("DEBUG")] makes the compiler drop every call to the method, including evaluation of its arguments, when the calling code is compiled without DEBUG. The method itself stays in the assembly, and the caller's symbols decide.

open as a page

In a C# library, how do you deprecate an old LogAsync overload with [Obsolete] and ship a preview API with [Experimental], and what do callers' builds report?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Mark the old overload [Obsolete("use X")] for warning CS0618, or error: true for CS0619; DiagnosticId and UrlFormat give it your own id and link. [Experimental("ID")], since .NET 8, makes each use a build error under that id until the caller suppresses it.

open as a page