skip to content

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%

answer

  1. reflection over a MemberInfo
  2. null, one, or ambiguous
  3. a fresh object per call
  4. properties ignore inherit sometimes

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.

solid answer

~40 s

Reading an attribute starts from reflection: `typeof(CheckoutService).GetMethod("PlaceOrder")` gives a `MethodInfo`, and the `CustomAttributeExtensions` method `GetCustomAttribute<TracedAttribute>()` returns the instance, or `null` when it is absent, and throws `AmbiguousMatchException` when the attribute appears more than once. `GetCustomAttributes<T>()` returns every match and `IsDefined(typeof(T))` answers presence without constructing anything. Matches include subclasses of `T`. The extension overloads default to `inherit: true`, which also searches base classes and overridden base methods, filtered by the attribute's `Inherited` setting. Two traps: every `GetCustomAttribute` call runs the constructor and returns a new object, so cache the result on hot paths; and `PropertyInfo.GetCustomAttributes(type, true)` ignores `inherit`, while `Attribute.GetCustomAttribute(property, type, true)` and the extension methods honour it.

code

csharp · 30 lines
csharp
using System.Reflection;

var run = typeof(PaymentsJob).GetMethod(nameof(PaymentsJob.Run))!;
Console.WriteLine($"IsDefined: {run.IsDefined(typeof(TracedAttribute))}");
var a = run.GetCustomAttribute<TracedAttribute>();
var b = run.GetCustomAttribute<TracedAttribute>();
Console.WriteLine($"same instance: {ReferenceEquals(a, b)}, operation: {a?.Operation}");

var status = typeof(PaymentsJob).GetProperty(nameof(JobBase.Status))!;
Console.WriteLine($"PropertyInfo.GetCustomAttributes(true): {status.GetCustomAttributes(typeof(TracedAttribute), true).Length}");
Console.WriteLine($"GetCustomAttribute<T>(): {status.GetCustomAttribute<TracedAttribute>()?.Operation}");

try { run.GetCustomAttribute<TagAttribute>(); }
catch (AmbiguousMatchException) { Console.WriteLine("two [Tag]s: use GetCustomAttributes<TagAttribute>()"); }

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
public sealed class TracedAttribute : Attribute
{
    public TracedAttribute(string operation) { Operation = operation; Console.WriteLine("  ctor ran"); }
    public string Operation { get; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class TagAttribute(string name) : Attribute { public string Name { get; } = name; }

public class JobBase { [Traced("job.status")] public virtual string Status => "idle"; }
public class PaymentsJob : JobBase
{
    public override string Status => "running";
    [Traced("payments.run"), Tag("payments"), Tag("nightly")] public void Run() { }
}

go deeper

for a junior

Know the basic shape: get a MemberInfo with typeof and GetMethod or GetProperty, then call GetCustomAttribute<T>() and check for null.

for a middle

Explain the single versus multiple APIs, AmbiguousMatchException, IsDefined, and what inherit: true walks for classes and overridden methods.

for a senior

Call out the per-call construction cost and caching, and the property and event asymmetry where the PropertyInfo override ignores inherit but the static Attribute methods honour it.

for a principal

Decide where attribute discovery happens in a codebase, a startup cache or a compile-time generator, so per-request reflection never becomes a hidden hot path.

## The reading API Attributes are metadata until something reads them. In .NET that reader is usually **reflection**: you obtain a `MemberInfo` (a `Type`, `MethodInfo`, `PropertyInfo`, `FieldInfo`, `EventInfo`), a `ParameterInfo`, a `Module` or an `Assembly`, then ask it for attributes. There are three families of methods: | API | Returns | Notes | |---|---|---| | `member.GetCustomAttribute<T>()` (extension in `System.Reflection.CustomAttributeExtensions`) | one `T` or `null` | throws `AmbiguousMatchException` if more than one matches; `inherit` defaults to `true` | | `member.GetCustomAttributes<T>()` | `IEnumerable<T>` | every match, including inherited ones | | `member.IsDefined(typeof(T))` | `bool` | presence only; does not run the attribute's constructor | | `Attribute.GetCustomAttribute(member, typeof(T), inherit)` | `Attribute?` | the static API the extensions call | | `MemberInfo.GetCustomAttributes(Type, bool)` | `object[]` | the virtual method each `MemberInfo` implements | | `member.GetCustomAttributesData()` | `CustomAttributeData` list | constructor and named arguments as data, no instance | All of them match by assignability: asking for `TracedAttribute` also returns an `AuditedTracedAttribute` that derives from it. ## Instances are built on every read The compiler stored the constructor reference and the argument values as a blob. Each call to `GetCustomAttribute<T>()` or `GetCustomAttributes<T>()` makes the runtime: 1. decode the blob, 2. run the attribute's constructor with the positional values, 3. assign the named properties and fields, 4. hand you a **new** object. Two calls on the same `MethodInfo` return two different instances (`ReferenceEquals` prints `False`). Because attribute objects can be mutable through their setters, a fresh copy keeps one reader from changing what another sees, but it also means a middleware or serializer that reads `[Traced]` per request allocates and runs constructors per request. The fix is to read once and cache, for example in a `ConcurrentDictionary<MethodInfo, TracedAttribute?>` or a static field initialised at startup. `IsDefined` avoids construction entirely, and `GetCustomAttributesData()` lets tooling inspect arguments without running attribute code. ## What inherit: true walks The `inherit` argument asks reflection to look beyond the declaration itself: - On a `Type`, it walks the base-class chain. - On an overriding method, it walks the overridden base method definitions. - Attributes whose `[AttributeUsage]` says `Inherited = false` are skipped by the walk. - Interfaces are not walked: an attribute on `IJob.Run` is not reported on `Impl.Run`. There is one long-standing asymmetry for **properties and events**. The runtime's own `PropertyInfo` and `EventInfo` implementations of `GetCustomAttributes(Type, bool)` ignore the `inherit` flag and return only the attributes declared on that exact member. The static `Attribute.GetCustomAttribute(s)` methods contain the extra code that finds the base property and walks it, and the `GetCustomAttribute<T>()` extensions call those static methods. So, for an overriding `Status` property whose base carries `[Traced]`: - `status.GetCustomAttributes(typeof(TracedAttribute), true).Length` is `0`. - `status.GetCustomAttribute<TracedAttribute>()` finds the base attribute. ## Single versus multiple `GetCustomAttribute<T>()` is for attributes that can appear at most once. If an attribute allows repetition (`AllowMultiple = true`) and two `[Tag]` attributes sit on one method, the singular call throws `AmbiguousMatchException` instead of guessing. Use `GetCustomAttributes<T>()` for those, and design the attribute's usage so the singular form is safe for single-use attributes. ## Walking through the example The snippet gives `TracedAttribute` a constructor that prints `ctor ran`, so you can see exactly when reflection builds an instance: 1. `run.IsDefined(typeof(TracedAttribute))` prints `True` and no `ctor ran` line: presence is answered from metadata. 2. Two `GetCustomAttribute<TracedAttribute>()` calls print `ctor ran` twice, and `ReferenceEquals` reports `False`. 3. On the overriding `Status` property, `PropertyInfo.GetCustomAttributes(typeof(TracedAttribute), true)` returns an empty array without constructing anything, while the extension method `GetCustomAttribute<TracedAttribute>()` constructs the base property's attribute and returns `job.status`. 4. `Run` carries two `[Tag]` attributes, so `GetCustomAttribute<TagAttribute>()` throws `AmbiguousMatchException`, and the catch block points to the plural method. Every line of that output comes from running the file on the .NET SDK 10.0.401; none of it depends on the build configuration, because attribute reading happens entirely at run time. ## Practical reading pattern - Read once per member at startup or on first use, then cache the result. - Use `IsDefined` when you only need a yes or no. - Prefer the `CustomAttributeExtensions` generic methods: they return typed results and honour `inherit` for properties. - Remember that reflection-based reading happens at run time; reflection over members and trimming concerns belong with the runtime type inspection material, and compile-time readers belong with source generators.

  • How would you avoid reading [Traced] through reflection on every request?
    Read it once per `MethodInfo` and cache the result, for example in a `ConcurrentDictionary<MethodInfo, TracedAttribute?>` filled on first use, or build a lookup at startup. Each `GetCustomAttribute<T>()` call runs the constructor and allocates a new instance, so a cache removes both costs. Moving discovery to compile time with a source generator is the other route.
  • How can a tool inspect an attribute's arguments without running its constructor?
    `MemberInfo.GetCustomAttributesData()` returns `CustomAttributeData` objects describing the attribute type, its constructor arguments (`ConstructorArguments`) and named arguments (`NamedArguments`) as data. No attribute code runs, which suits analyzers, documentation tools and code that must not trigger side effects. `IsDefined` likewise checks presence without instantiating.
  • Why might GetCustomAttribute<TracedAttribute>() return an instance of a different class?
    Matching is by assignability: any attribute whose type derives from `TracedAttribute`, such as an `AuditedTracedAttribute`, satisfies the request. That is one reason the CA1813 rule asks you to seal attribute classes unless derivation is intended: lookups must consider subclasses, and readers may receive a type they did not expect.

  • Assumes GetCustomAttribute returns the first match when there are several
  • Believes the runtime caches attribute instances, so repeated reads are free
  • Expects PropertyInfo.GetCustomAttributes(type, true) to search the base property
  • Thinks IsDefined has to construct the attribute to answer
  • Believes inherit: true also searches implemented interfaces