skip to content

In C#, how can a custom interpolated string handler make trace.Write($"Rendering {Describe()}") skip all formatting when tracing is off?

level: seniorimportance: should knowfreq 33%

answer

  1. a parameter type, not a string
  2. constructor sees the receiver
  3. a trailing out bool
  4. holes may never run

basics

~20 s

Since C# 10, a $"" passed to a handler-typed parameter becomes a handler constructor call plus AppendLiteral and AppendFormatted calls. A constructor that gets the receiver through [InterpolatedStringHandlerArgument("")] and sets out bool shouldAppend to false skips every hole.

solid answer

~40 s

Declare `Write(TraceHandler message)` instead of `Write(string)`, where `TraceHandler` is a `ref struct` marked `[InterpolatedStringHandler]`. The compiler then emits `new TraceHandler(literalLength, formattedCount, trace, out bool shouldAppend)` at the call site; `[InterpolatedStringHandlerArgument("")]` on the parameter is what passes `trace` in. If the constructor sets `shouldAppend` to `false`, the compiler skips every `AppendLiteral` and `AppendFormatted` call, so no hole is evaluated, nothing is formatted, and this handler allocates nothing. The catch is that `Describe()` does not run at all, so a hole with a side effect now behaves differently when tracing is off. Ordinary `string` interpolation uses the same pattern through `DefaultInterpolatedStringHandler`, which pools its buffer and formats value types without boxing.

code

csharp · 47 lines
csharp
using System.Runtime.CompilerServices;
using System.Text;

var trace = new RenderTrace { Enabled = false };
int calls = 0;
string Describe() { calls++; return "page 3 layout"; }

trace.Write($"Rendering {Describe()} at {DateTime.UtcNow:O}");        // handler overload
trace.WriteString($"Rendering {Describe()} at {DateTime.UtcNow:O}");  // string overload
Console.WriteLine($"disabled: Describe() ran {calls} time(s)");

long before = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 1000; i++) trace.Write($"Line {i} total {i * 1.5m:N2}");
long viaHandler = GC.GetAllocatedBytesForCurrentThread() - before;
before = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 1000; i++) trace.WriteString($"Line {i} total {i * 1.5m:N2}");
long viaString = GC.GetAllocatedBytesForCurrentThread() - before;
Console.WriteLine($"handler: {viaHandler} bytes, string: {viaString > 0}");

trace.Enabled = true;
trace.Write($"Rendering {Describe()} at {new DateTime(2026, 10, 26):yyyy-MM-dd}");

public sealed class RenderTrace
{
    public bool Enabled { get; set; }
    public void Write([InterpolatedStringHandlerArgument("")] TraceHandler message)
    {
        if (Enabled) Console.WriteLine(message.ToStringAndClear());
    }
    public void WriteString(string message) { if (Enabled) Console.WriteLine(message); }
}

[InterpolatedStringHandler]
public ref struct TraceHandler
{
    private StringBuilder? _builder;
    public TraceHandler(int literalLength, int formattedCount, RenderTrace trace, out bool shouldAppend)
    {
        shouldAppend = trace.Enabled;
        _builder = shouldAppend ? new StringBuilder(literalLength) : null;
    }
    public void AppendLiteral(string value) => _builder!.Append(value);
    public void AppendFormatted<T>(T value) => _builder!.Append(value);
    public void AppendFormatted<T>(T value, string? format) where T : IFormattable =>
        _builder!.Append(value.ToString(format, null));
    public string ToStringAndClear() => _builder?.ToString() ?? "";
}

go deeper

for a junior

Recall that interpolation does not always mean string.Format and that a method can receive an interpolated string as something other than a string.

for a middle

Explain the lowering: a handler constructed with literal length and hole count, AppendLiteral and AppendFormatted calls, then ToStringAndClear.

for a senior

Write a handler with InterpolatedStringHandlerArgument and out bool, prove the saving with allocated-bytes counts, and flag holes whose side effects disappear when it declines.

for a principal

Decide where a custom handler earns its complexity, such as hot diagnostic paths, and where a plain string parameter keeps the code easier for the team to maintain.

## What the compiler does with an interpolated string Since C# 10, an interpolated string is not always a call to `string.Format`. For a `$"..."` whose type is `string`, the C# 14 compiler in the .NET 10 SDK picks one of five lowerings, in this order: 1. **A constant**, when every part is a constant string (this is also what lets `const string Key = $"{Prefix}-number";` compile in C# 10 and later). 2. **`string.Concat`**, when there are at most four parts and every hole is a `string` with no width or format. 3. **`DefaultInterpolatedStringHandler`**, the usual case on .NET 6 and later, unless a hole contains `await` or the string sits in an exception filter. 4. **`string.Concat`** over an array, for more than four all-string parts when the handler cannot be used. 5. **`string.Format`**, the pre-C# 10 strategy, as the last fallback. The docs page for `$` still says the compiler "typically" emits `string.Format`; the compiler source shows the handler is preferred whenever it is available. ## DefaultInterpolatedStringHandler `System.Runtime.CompilerServices.DefaultInterpolatedStringHandler` is a `ref struct` that the compiler drives like this: - Its constructor receives `literalLength` (characters of literal text) and `formattedCount` (number of holes) and, unless the caller supplies an initial `Span<char>` buffer, rents a `char[]` of at least 256 characters from `ArrayPool<char>.Shared`. - Each literal piece becomes `AppendLiteral(string)`; each hole becomes an `AppendFormatted` call whose overload carries the value, the width (parameter name `alignment`) and the format string. - `AppendFormatted<T>` is generic, so a value type is not boxed: after checking for an `ICustomFormatter` from the provider, it prefers `ISpanFormattable.TryFormat`, writing straight into the buffer, and falls back to `IFormattable.ToString` and then `ToString()`. - `ToStringAndClear()` creates the result string and returns the array to the pool. ## Writing a handler that can say no The same pattern works for your own types. Any parameter whose type is a **handler** makes the compiler build the handler at the call site instead of building a string: 1. Mark a type (usually a `ref struct`) with **`[InterpolatedStringHandler]`**. 2. Give it a constructor `(int literalLength, int formattedCount, ...)`. Extra parameters are filled from the call: **`[InterpolatedStringHandlerArgument("")]`** on the method's parameter passes the receiver, and a parameter name passes that argument. 3. End the constructor with **`out bool shouldAppend`** (any name). If it is set to `false`, the compiler skips every `AppendLiteral` and `AppendFormatted` call. 4. Provide `AppendLiteral(string)` and the `AppendFormatted` overloads your holes need, for example one with a `string? format` parameter for `{when:O}`. In the snippet, `RenderTrace.Write` takes a `TraceHandler`. With tracing off, a thousand calls allocate **0 bytes**, while the same calls through a `string` parameter allocate a formatted string every time. ## The price: holes that never run Skipping the appends means **the hole expressions are not evaluated**. `Describe()` in the snippet ran once, from the call made through the `string` overload, and not at all through the handler while tracing was off. That is the point, and also a review hazard: a hole that increments a counter or reads a stream has a side effect that now depends on configuration. The docs for `$` state the same caveat for every handler, `DefaultInterpolatedStringHandler` included. ## Rules the compiler enforces - `AppendLiteral` and `AppendFormatted` must return `void` or `bool` (**CS8941**), and all of them the same one (**CS8942**). Returning `bool` lets the handler stop after any part, which is finer-grained than the constructor's `out bool`. - A type used as a handler without the attribute is **CS8946**, "Type is not an interpolated string handler type." - A parameter named in `InterpolatedStringHandlerArgument` that comes after the handler parameter draws warning **CS8947**, because callers would have to reorder arguments with names. - If a method has both a `string` overload and a handler overload, a non-constant `$"..."` argument binds to the **handler**, while a constant `$"text"` binds to the string overload. ## When it is worth it A custom handler pays off on hot paths where most messages are discarded: trace and assertion helpers, or a renderer's diagnostic output called once per line of a large document. Elsewhere, a plain `string` parameter is simpler to read, and the default handler already avoids boxing and pools its buffer.

  • What does the compiler emit for string s = $"{count} items"; with an int count, targeting .NET 10?
    A `DefaultInterpolatedStringHandler` built with the literal length and one hole, then `AppendFormatted(count)` and `AppendLiteral(" items")`, then `ToStringAndClear()`. `string.Concat` is used only when every hole is a string without width or format, and `string.Format` only as a fallback, for example when a hole contains `await`.
  • What do bool-returning AppendLiteral and AppendFormatted methods add?
    Per-part short-circuiting: each call returns whether to continue, and after a `false` the compiler skips the remaining parts, so a handler can stop once a buffer is full. All append methods must use the same return type; mixing `void` and `bool` is CS8942.
  • If RenderTrace also had Write(string), which overload would trace.Write($"Line {i}") pick?
    The handler overload, because a non-constant interpolated string prefers an interpolated string handler conversion. A constant interpolated string such as `$"Constant text"` binds to `Write(string)`, since it can be emitted as a literal with no handler at all.

  • An interpolated string argument is always fully built before the method is called.
  • C# interpolation always lowers to string.Format and boxes value-type holes.
  • Skipping holes is harmless because interpolation expressions cannot have side effects.
  • A handler must be a class so it can keep state between Append calls.
  • Interpolated string handlers are a C# 14 feature that needs .NET 10.