Skip to content

C# strings: interpolation, raw and UTF-8 literals

Building text is everywhere in an OrdersPortal application: receipts, log lines, SQL, JSON payloads, protocol headers. This page covers the C# features that change how string content is written and built: interpolation for readable formatting, raw string literals for text full of quotes and braces, interpolated string handlers for APIs that want to avoid building strings they will not use, and UTF-8 literals for code that works with bytes rather than string.

Every complete sample is a file-based program: save it as sample.cs and run dotnet run sample.cs with the .NET 10 SDK (C# 14). All samples on this page were compiled and run with .NET SDK 10.0.115.

Feature Version Use it when
String interpolation C# 6 You format values into text for people to read.
Raw string literals C# 11 The text contains quotes, backslashes, braces or several lines.
Interpolated string handlers C# 10 You write an API that should skip or customize formatting work.
UTF-8 string literals C# 11 An API takes UTF-8 bytes, such as a protocol writer or JSON writer.

Introduced in C# 6 (.NET Framework 4.6). An interpolated string, $"Order {orderId} total {total:0.00}", embeds expressions in braces, and each hole can take an alignment and a format: {value,alignment:format}. A positive alignment right-aligns in that many characters, a negative one left-aligns, and the format is any standard or custom .NET format string. Write {{ and }} for literal braces.

Formatting uses the current culture, so {total:N2} prints 84.98 on one machine and 84,98 on another. For file formats, APIs and logs that other programs parse, use string.Create(CultureInfo.InvariantCulture, $"...") or FormattableString.Invariant(...). Since C# 10 an interpolated string whose holes are all constant strings can initialize a const, and since C# 11 a hole can span several lines, which helps with longer expressions such as a switch expression.

using System.Globalization;
var lines = new (string Sku, int Qty, decimal Price)[]
{
("SKU-RED-01", 2, 19.99m),
("SKU-BLUE-22", 10, 4.5m),
};
foreach (var (sku, qty, price) in lines)
{
// {value,alignment:format}: negative alignment = left-aligned
Console.WriteLine($"{sku,-12}|{qty,4}|{price,8:0.00}|{qty * price,9:0.00}");
}
decimal total = 0;
foreach (var line in lines) total += line.Qty * line.Price;
var orderDate = new DateTime(2026, 11, 18);
// Culture-independent text for files and APIs
string invariant = string.Create(CultureInfo.InvariantCulture, $"Total {total:N2} on {orderDate:yyyy-MM-dd}");
string german = string.Create(new CultureInfo("de-DE"), $"Summe {total:N2}");
Console.WriteLine(invariant);
Console.WriteLine(german);
Console.WriteLine($"Use {{orderId}} placeholders in templates, e.g. {{1001}}");
const string Prefix = "ORD";
const string Route = $"/api/{Prefix}/"; // constant interpolated string (C# 10)
Console.WriteLine(Route);

Output:

SKU-RED-01 | 2| 19.99| 39.98
SKU-BLUE-22 | 10| 4.50| 45.00
Total 84.98 on 2026-11-18
Summe 84,98
Use {orderId} placeholders in templates, e.g. {1001}
/api/ORD/

Pitfalls:

  • Culture leaks into data. Interpolating a decimal or DateTime into CSV, JSON or a URL without an explicit culture breaks on machines with a different locale.
  • Not for SQL or HTML. Interpolating user input into SQL is injection; use parameters (or an API such as EF Core’s FromSql, which turns the holes into parameters). For HTML, use an encoder.
  • Not for ILogger message templates. logger.LogInformation($"Order {id}") loses structured logging fields and always builds the string; pass a template and arguments instead (analyzer CA2254).

Introduced in C# 11 (.NET 7). A raw string literal starts and ends with at least three double quotes and contains no escape sequences: backslashes and quotes are literal text. If the content contains three quotes in a row, open and close with four, and so on. A multi-line raw string puts the opening and closing quotes on their own lines, and the whitespace before the closing quotes is removed from every content line, so the literal can be indented with the surrounding code without that indentation ending up in the string.

Raw strings can be interpolated. The number of $ signs sets how many braces open a hole: with $$""", single { and } are literal text and {{expr}} is a hole, which is exactly what JSON templates need. Single-line raw strings ("""^ORD-\d{4}$""") are handy for regular expressions.

int orderId = 1001;
string customer = "Ada \"The Analyst\" Lopez";
string query = """
SELECT Id, Total
FROM Orders
WHERE Status = 'Shipped'
AND Notes LIKE '%"gift"%'
""";
Console.WriteLine(query);
// $$ means interpolation holes use {{ }}, so single { } stay literal JSON braces.
string payload = $$"""
{
"orderId": {{orderId}},
"customer": "{{customer.Replace("\"", "\\\"")}}",
"tags": ["priority", "gift"]
}
""";
Console.WriteLine(payload);
string pattern = """^ORD-\d{4}-[A-Z]{2}$"""; // single-line raw string: no escaping in regex
Console.WriteLine(System.Text.RegularExpressions.Regex.IsMatch("ORD-1001-PT", pattern));

Output:

SELECT Id, Total
FROM Orders
WHERE Status = 'Shipped'
AND Notes LIKE '%"gift"%'
{
"orderId": 1001,
"customer": "Ada \"The Analyst\" Lopez",
"tags": ["priority", "gift"]
}
True

Pitfalls:

  • Indentation must line up. Every content line must start with the same whitespace as the closing quotes, or the compiler reports an error.
  • Templates are not serializers. The sample escapes quotes by hand to stay short; for real JSON from user data, use System.Text.Json so every special character is escaped correctly.
  • No line break at the ends. The newline after the opening quotes and before the closing quotes is not part of the value.

Introduced in C# 10 (.NET 6). Normally an interpolated string is converted to a string before the method you pass it to even runs. An interpolated string handler changes that: when a parameter’s type is a handler (a type marked [InterpolatedStringHandler]), the compiler instead constructs the handler and calls its AppendLiteral and AppendFormatted methods piece by piece. With [InterpolatedStringHandlerArgument] the handler’s constructor can receive other arguments, such as the logger and level, and set an out bool shouldAppend to false so that no hole is evaluated at all.

.NET uses this for StringBuilder.Append, Debug.Assert, string.Create and MemoryExtensions.TryWrite, and DefaultInterpolatedStringHandler makes ordinary $"..." strings cheaper than string.Format. Application code mostly benefits without noticing; you write a handler when you own an API where formatting is often unnecessary or needs special treatment.

using System.Runtime.CompilerServices;
using System.Text;
var audit = new AuditLog { MinimumLevel = AuditLevel.Info };
int lookups = 0;
audit.Write(AuditLevel.Info, $"Order {1001} approved by {"ops-team"}");
audit.Write(AuditLevel.Debug, $"Cart snapshot: {ExpensiveSnapshot()}"); // skipped entirely
Console.WriteLine($"Snapshot built {lookups} times");
var sb = new StringBuilder();
sb.Append($"Order {1002} total {80.5m:0.00}"); // StringBuilder's handler appends parts directly
Console.WriteLine(sb);
string ExpensiveSnapshot()
{
lookups++;
return "{...}";
}
enum AuditLevel { Debug, Info, Warning }
class AuditLog
{
public AuditLevel MinimumLevel { get; init; }
public void Write(AuditLevel level,
[InterpolatedStringHandlerArgument("", "level")] AuditHandler message)
{
if (message.Enabled)
Console.WriteLine($"[{level}] {message.GetText()}");
}
}
[InterpolatedStringHandler]
ref struct AuditHandler
{
private readonly StringBuilder? _builder;
public bool Enabled { get; }
public AuditHandler(int literalLength, int formattedCount, AuditLog log, AuditLevel level, out bool shouldAppend)
{
Enabled = level >= log.MinimumLevel;
shouldAppend = Enabled; // false: compiler skips every Append call
_builder = Enabled ? new StringBuilder(literalLength) : null;
}
public void AppendLiteral(string text) => _builder!.Append(text);
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));
internal string GetText() => _builder?.ToString() ?? "";
}

Output:

[Info] Order 1001 approved by ops-team
Snapshot built 0 times
Order 1002 total 80.50

The Debug call never constructs a StringBuilder and never calls ExpensiveSnapshot(), because the handler set shouldAppend to false.

Pitfalls:

  • ILogger extension methods do not use handlers. LogDebug($"...") from Microsoft.Extensions.Logging takes a plain string, so the message is always built. Use message templates or the [LoggerMessage] source generator there.
  • Side effects may not run. In the sample ExpensiveSnapshot() is never called; code that relies on a side effect inside a hole breaks when the level changes.
  • Evaluation order can change. Moving a call to a handler overload means holes are evaluated and appended one by one, which changed behavior for some StringBuilder.Append calls in .NET 6.

Introduced in C# 11 (.NET 7). Adding the u8 suffix to a string literal, "PING"u8, makes the compiler encode it as UTF-8 at compile time. The result is a ReadOnlySpan<byte> that points at bytes stored in the assembly, so there is no Encoding.UTF8.GetBytes call and no allocation at run time. This suits code that speaks UTF-8 on the wire: protocol writers, Utf8JsonWriter property names, HTTP headers, and comparisons against incoming byte buffers.

Remember the byte count is not the character count: ASCII characters take one byte each, but € takes three. Call .ToArray() when you need a byte[] that outlives the span or must be stored in a field of a class.

using System.Text;
ReadOnlySpan<byte> header = "ORDERS-v1\n"u8;
Console.WriteLine($"Header bytes: {header.Length}");
Console.WriteLine($"First bytes: {Convert.ToHexString(header[..4])}");
byte[] incoming = Encoding.UTF8.GetBytes("ORDERS-v1\n1001;café;2\n");
bool valid = incoming.AsSpan().StartsWith(header);
Console.WriteLine($"Valid export header: {valid}");
ReadOnlySpan<byte> euro = "€"u8; // one char, three UTF-8 bytes
Console.WriteLine($"'€' is {euro.Length} bytes: {Convert.ToHexString(euro)}");
using var stream = new MemoryStream();
stream.Write("STATUS OK\r\n"u8); // no encoder call, no string allocation
Console.WriteLine($"Wrote {stream.Length} bytes");
byte[] stored = "PING"u8.ToArray(); // copy when you need a byte[] that outlives the span
Console.WriteLine(Encoding.UTF8.GetString(stored));

Output:

Header bytes: 10
First bytes: 4F524445
Valid export header: True
'€' is 3 bytes: E282AC
Wrote 11 bytes
PING

Pitfalls:

  • Not a constant. A u8 literal cannot be a const or a default parameter value (error CS1736).
  • No interpolation. $"..."u8 does not compile; build dynamic UTF-8 with Utf8.TryWrite or a UTF-8 writer instead.
  • Span rules apply. A ReadOnlySpan<byte> cannot be stored in a class field or captured across await; copy it with .ToArray() when needed.
  • Human-readable messages: string interpolation, with an explicit culture when the text is data.
  • Embedded JSON, SQL, XML or regular expressions: raw string literals, interpolated with $$ when braces appear in the content.
  • Library APIs where formatting is often wasted (diagnostics, assertions, builders): an interpolated string handler.
  • Bytes on the wire: UTF-8 literals; convert to string only at the edges where you need one.

How do you make an interpolated string culture-invariant? Use string.Create(CultureInfo.InvariantCulture, $"...") or FormattableString.Invariant($"..."). A plain $"..." uses the current culture for numbers and dates.

How does a raw string literal decide how much indentation to remove? The whitespace in front of the closing quotes is removed from the start of every content line. Every content line must begin with that same whitespace.

What does $$""" change? It sets the number of braces that open an interpolation hole to two, so single { and } are literal. The number of $ signs always equals the number of braces needed for a hole.

What problem do interpolated string handlers solve, and who should write them? They let the receiving API control how, or whether, an interpolated string is built, avoiding allocations and skipping evaluation of holes when the result is not needed. Library and framework authors write them; most application developers benefit through StringBuilder, Debug.Assert and similar APIs.

What is the type of "abc"u8? ReadOnlySpan<byte> containing the UTF-8 encoding of the text. It is not a string, not a byte[] and not a compile-time constant.

Senior scenario: a profiler shows OrdersPortal’s request logging allocates heavily even when debug logging is off. What do you change? Check for interpolated strings passed to ILogger methods: they are built before the call, whatever the level. Switch to message templates with arguments, or better, [LoggerMessage] source-generated methods, which check IsEnabled and avoid boxing. Guard genuinely expensive values with logger.IsEnabled(LogLevel.Debug). If the team owns its own logging facade, an interpolated string handler with [InterpolatedStringHandlerArgument] gives the same “free when disabled” behavior while keeping $"..." call sites.