C# & ADO.NET

C# string interpolation: $"", format specifiers, raw strings and performance

C# & ADO.NET · · Published 2026-12-06 · Updated 2026-12-06

String interpolation is the way most C# code builds text today: a $ in front of a string literal, expressions in braces, and the compiler does the rest. It looks simple, and for a log line or a label it is. The details start to matter when you format money for a French customer, generate JSON in a test, or write a log statement that runs a million times an hour. This guide covers the syntax from the basics to raw interpolated strings, then the rules that keep the output correct and the code fast.

The basics: $"" and expressions in braces

An interpolated string is a string literal prefixed with $. Anything inside { } is a C# expression; its value is converted to text and inserted at that position.

string customer = "Lena";
int items = 3;
decimal total = 59.9m;

string message = $"{customer} ordered {items} items for {total} euros.";
// Lena ordered 3 items for 59.9 euros.  (the decimal separator depends on the current culture)

The expression can be anything that returns a value: a property, a method call, arithmetic, or a conditional. A conditional needs its own parentheses, because a colon inside the braces would otherwise be read as the start of a format specifier.

string label = $"{items} item{(items == 1 ? "" : "s")} in your basket";
string upper = $"Hello, {customer.ToUpperInvariant()}!";
string sum   = $"Subtotal with VAT: {total * 1.2m:F2}";

Interpolation arrived in C# 6 (Visual Studio 2015) as a replacement for string.Format("{0} ordered {1} items", customer, items), where every placeholder had to match an argument by position. The official reference is the Microsoft Learn page on interpolated strings, which also lists which features need which language version.

Alignment and format specifiers

Inside the braces, the full form is {expression,alignment:format}. Both parts are optional.

var rows = new[] { ("Keyboard", 49.5m), ("Monitor", 189m), ("USB-C cable", 9.99m) };

foreach (var (name, price) in rows)
    Console.WriteLine($"{name,-14}|{price,10:N2}");

// Keyboard      |     49.50
// Monitor       |    189.00
// USB-C cable   |      9.99

DateTime shipped = new DateTime(2026, 12, 6);
Console.WriteLine($"Shipped on {shipped:yyyy-MM-dd}, invoice {1042:D6}, discount {0.125:P1}");
// Shipped on 2026-12-06, invoice 001042, discount 12.5 %   (spacing of % depends on culture)

The format codes are documented in the standard numeric format strings reference; dates have their own standard and custom format tables. Alignment is handy for console tools and plain-text e-mails, less so for HTML, where a table or CSS does the job.

Culture: the bug that ships to production

An interpolated string formats numbers and dates with the current culture of the thread. On a developer machine set to English, $"{1234.5}" gives 1234.5. On a server or a user session set to French or German, it gives 1234,5. That is correct for text shown to a person, and wrong for anything a program reads back: a CSV file, a SQL string, a query-string parameter, a JSON value written by hand.

Since .NET 6, the clean way to choose the culture is string.Create with a format provider:

using System.Globalization;

decimal price = 1234.5m;

string forMachines = string.Create(CultureInfo.InvariantCulture, $"price={price}");
// price=1234.5 on every server

string forFrench = string.Create(new CultureInfo("fr-FR"), $"{price:C}");
// 1 234,50 €

On older frameworks, the equivalent is FormattableString.Invariant($"..."), or assigning the interpolated string to a FormattableString and calling ToString(provider). In an ASP.NET Web Forms application, remember that the culture often comes from <globalization culture="auto" /> in web.config, so the same page can format differently for two visitors; our web.config guide covers that setting.

Literal braces, quotes and multi-line strings

To print a brace in an ordinary interpolated string, double it: {{ gives { and }} gives }.

string css = $".alert {{ color: {color}; }}";   // .alert { color: red; }

Combine $ with @ for a verbatim interpolated string, useful for Windows paths and regular expressions. Since C# 8 the order does not matter: $@"..." and @$"..." are the same.

string path = $@"C:\Exports\{DateTime.Today:yyyyMMdd}\orders.csv";

Since C# 11, the expression inside the braces may also span several lines, which helps with long LINQ calls or switch expressions, although extracting a variable is usually more readable.

Raw interpolated strings (C# 11)

Doubling braces becomes painful as soon as the text is JSON, a C# snippet or a CSS block. C# 11 added raw string literals: text between at least three double quotes, with no escaping at all. For interpolation, the number of $ signs says how many braces open an expression.

int id = 42;
string name = "Lena";

string json = $$"""
    {
      "id": {{id}},
      "name": "{{name}}",
      "tags": { "vip": true }
    }
    """;

With $$, a single { is plain text and {{id}} is an expression. The closing """ sets the indentation: every line loses the whitespace that precedes it, so the string can follow the code's indentation without carrying it into the output. Raw strings are excellent for test fixtures and templates. For real JSON sent over the wire, prefer a serializer such as System.Text.Json: interpolation does not escape quotes or backslashes inside name.

Performance: what changed in .NET 6

Until C# 9, the compiler turned most interpolated strings into a call to string.Format. That meant parsing the format string at run time, an object[] array, and boxing every value type. C# 10 and .NET 6 introduced interpolated string handlers: the compiler now emits a series of AppendLiteral and AppendFormatted calls on DefaultInterpolatedStringHandler, a struct that writes into a pooled buffer. In the announcement post on the .NET blog, Stephen Toub sums it up: creating strings with interpolation "gets faster and more memory efficient", without any change to source code; you only need to recompile against .NET 6 or later (String Interpolation in C# 10 and .NET 6).

Practical consequences:

The handler pattern is explained step by step in the Microsoft Learn tutorial on writing a custom interpolated string handler.

Logging: do not interpolate the message template

One place where interpolation is the wrong tool is structured logging with Microsoft.Extensions.Logging, Serilog or NLog.

// Avoid: the text is built even when Debug is disabled, and the values are lost as fields
_logger.LogDebug($"Order {orderId} shipped to {country}");

// Prefer: a constant template with named placeholders
_logger.LogDebug("Order {OrderId} shipped to {Country}", orderId, country);

With the template form, the logger can skip all the work when the level is off, and log stores such as Seq or Application Insights keep OrderId and Country as searchable properties. The .NET analyzers flag the interpolated version with rule CA2254: template should be a static expression.

Interpolation is not a query builder

A classic mistake in ADO.NET code is building SQL with $"SELECT * FROM Orders WHERE Customer = '{name}'". That is a SQL injection hole, whatever the syntax used to glue the strings. Use parameters (cmd.Parameters.AddWithValue("@name", name)), as shown in our ADO.NET data access guide. Entity Framework Core is an exception by design: FromSqlInterpolated and FromSql accept a FormattableString and turn each hole into a real parameter. The same caution applies to HTML: in Web Forms, an interpolated string written with Response.Write is not encoded, so pass user input through HttpUtility.HtmlEncode first.

Cheat sheet

You wantWriteSince
Insert a value$"Hi {name}"C# 6
Two decimals, thousands separator$"{total:N2}"C# 6
Right-align in 10 characters$"{total,10}"C# 6
Conditional text$"{(ok ? "yes" : "no")}"C# 6
Literal brace$"{{ {x} }}"C# 6
Path or regex$@"C:\Logs\{day}"C# 6 (@$ since C# 8)
Culture-independent outputstring.Create(CultureInfo.InvariantCulture, $"...").NET 6
Constant interpolated stringconst string Route = $"{Base}/orders";C# 10
JSON or code template$$"""{ "id": {{id}} }"""C# 11

For the rest of the string toolbox, from comparison rules to splitting and conversion, go back to our pillar guide on working with strings in C#. If the text you build is later handed to a native library, read strings in C, C++ and C# for what happens at the P/Invoke boundary.