csharp / expert
Snippet
Custom Interpolated String Handlers for Performance
Interpolated String Handlers (C# 10) allow you to take control of how interpolated strings are processed. By using an 'out bool enabled' parameter in the constructor, you can completely skip the evaluation of the string and its arguments (like expensive method calls) if a certain condition—such as a log level check—is not met, preventing unnecessary allocations and computations.
snippet.csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
[InterpolatedStringHandler]public struct LogHandler {public LogHandler(int literalLength, int holeCount, Logger log, out bool enabled) {enabled = log.IsEnabled;}public void AppendLiteral(string s) => Console.Write(s);public void AppendFormatted<T>(T value) => Console.Write(value);}public void Log(LogHandler handler) { }// Usagelogger.Log($"Data: {expensiveOperation()}"); // expensiveOperation is NOT called if logger is disabled
Breakdown
1
[InterpolatedStringHandler]
Marks the struct as a valid handler for interpolated string conversions.
2
out bool enabled
If set to false, the compiler skips calling Append methods and evaluating interpolated expressions.
3
AppendFormatted<T>(T value)
Called by the compiler for each expression (the 'holes') within the interpolated string.