C# string interpolation
last modified November 6, 2026
In this article we show how to build strings with string interpolation in C#.
String interpolation embeds expressions in a string literal. The
expressions are evaluated and their results are inserted into the string. A
string prefixed with the $ character is an interpolated string,
and the embedded expressions, called interpolation holes, are enclosed
in curly braces {}.
An interpolation hole has the following structure:
{<interpolationExpression>[,<alignment>][:<formatString>]}
The interpolationExpression produces the value to insert. The
optional alignment is the minimum width of the inserted text; a
positive value aligns it to the right and a negative value to the left. The
optional formatString is a standard or custom format specifier
supported by the value's type.
C# string interpolation simple example
The first example inserts variables and an expression into strings.
string name = "John Doe";
int age = 34;
Console.WriteLine($"{name} is {age} years old");
string msg = $"{name} will be {age + 1} next year";
Console.WriteLine(msg);
string old = string.Format("{0} is {1} years old", name, age);
Console.WriteLine(old);
We build three strings from a name and an age.
Console.WriteLine($"{name} is {age} years old");
The $ prefix marks the interpolated string. The variables are
inserted in place of the curly braces.
string msg = $"{name} will be {age + 1} next year";
A hole can contain any expression that produces a value.
string old = string.Format("{0} is {1} years old", name, age);
Interpolated strings replace composite formatting with numbered placeholders. They are easier to read, and the compiler checks the expressions.
$ dotnet run John Doe is 34 years old John Doe will be 35 next year John Doe is 34 years old
Alignment
The alignment component pads the value with spaces to the given width. It is useful for printing tables in the console.
List<User> users =
[
new("John", "Doe", 1230),
new("Lucy", "Novak", 670),
new("Ben", "Walter", 2050),
new("Robin", "Brown", 2300),
new("Amy", "Doe", 1250),
new("Albert", "Novak", 1930),
];
Console.WriteLine($"|{"Name",-15}|{"Salary",8}|");
Console.WriteLine($"|{new string('-', 15)}|{new string('-', 8)}|");
foreach (var user in users)
{
string fname = $"{user.FirstName} {user.LastName}";
Console.WriteLine($"|{fname,-15}|{user.Salary,8}|");
}
record User(string FirstName, string LastName, int Salary);
We print a table of users with left-aligned names and right-aligned salaries.
Console.WriteLine($"|{fname,-15}|{user.Salary,8}|");
The name occupies at least 15 characters and is left-aligned; the salary is right-aligned in eight characters. A value longer than the width is not cut.
$ dotnet run |Name | Salary| |---------------|--------| |John Doe | 1230| |Lucy Novak | 670| |Ben Walter | 2050| |Robin Brown | 2300| |Amy Doe | 1250| |Albert Novak | 1930|
Number format strings
The format string follows a colon. Numbers support standard format specifiers
such as C, F, N, and P, and
custom specifiers built from 0, #, and
,.
double price = 49.99;
int quantity = 3;
double ratio = 0.2567;
int val = 255;
Console.WriteLine($"Total cost: {price * quantity:C2}");
Console.WriteLine($"Price per item: {price:F1}");
Console.WriteLine($"Quantity: {quantity:D3}");
Console.WriteLine($"Big number: {1234567.891:N2}");
Console.WriteLine($"Ratio: {ratio:P1}");
Console.WriteLine($"Hex: {val:X} {val:x4}");
Console.WriteLine($"Scientific: {1234567.891:E3}");
Console.WriteLine($"Custom: {price:000.000} {1234567:#,##0}");
Console.WriteLine($"Aligned: [{price,10:F2}] [{price,-10:F2}]");
We format numbers as currency, fixed-point, padded integer, grouped number, percentage, hexadecimal, and scientific values.
Console.WriteLine($"Total cost: {price * quantity:C2}");
Console.WriteLine($"Price per item: {price:F1}");
The number after the specifier is the precision. C2 is currency
with two decimal places; F1 rounds the price to one decimal
place.
Console.WriteLine($"Quantity: {quantity:D3}");
For integers, D3 pads the value with zeros to three digits.
Console.WriteLine($"Ratio: {ratio:P1}");
The P specifier multiplies the number by 100 and adds a percent
sign.
Console.WriteLine($"Hex: {val:X} {val:x4}");
The X specifier produces upper-case and x lower-case
hexadecimal digits.
Console.WriteLine($"Aligned: [{price,10:F2}] [{price,-10:F2}]");
Alignment and format string can be combined. The alignment comes first.
$ dotnet run Total cost: $149.97 Price per item: 50.0 Quantity: 003 Big number: 1,234,567.89 Ratio: 25.7% Hex: FF 00ff Scientific: 1.235E+006 Custom: 049.990 1,234,567 Aligned: [ 49.99] [49.99 ]
Date and time format strings
DateTime values support standard specifiers such as
d and T, and custom patterns such as
yyyy-MM-dd.
var dt = new DateTime(2026, 11, 6, 14, 35, 12);
Console.WriteLine($"Short date: {dt:d}");
Console.WriteLine($"Long date: {dt:D}");
Console.WriteLine($"Short time: {dt:t}");
Console.WriteLine($"Long time: {dt:T}");
Console.WriteLine($"Month/day: {dt:M}");
Console.WriteLine($"Year/month: {dt:Y}");
Console.WriteLine($"ISO 8601: {dt:yyyy-MM-ddTHH:mm:ss}");
Console.WriteLine($"Custom: {dt:dddd, MMMM d} at {dt:HH:mm}");
We format a fixed date and time in various ways.
Console.WriteLine($"ISO 8601: {dt:yyyy-MM-ddTHH:mm:ss}");
The format string may contain colons; everything after the first colon belongs
to the format. In custom patterns, MM is the month and
mm the minutes, HH is the hour on a 24-hour clock.
Console.WriteLine($"Custom: {dt:dddd, MMMM d} at {dt:HH:mm}");
The dddd pattern is the full day name and MMMM the
full month name.
The standard formats depend on the current culture; the output was produced
with en-US.
$ dotnet run Short date: 11/6/2026 Long date: Friday, November 6, 2026 Short time: 2:35 PM Long time: 2:35:12 PM Month/day: November 6 Year/month: November 2026 ISO 8601: 2026-11-06T14:35:12 Custom: Friday, November 6 at 14:35
Escaping braces
To include a literal curly brace in an interpolated string, we double it.
int x = 5;
Console.WriteLine($"{{x}} is {x}");
Console.WriteLine($"{{{x}}}");
string path = @"C:\Users\Jan";
Console.WriteLine($@"{path}\Documents");
Console.WriteLine($"{path}\\Documents");
We print braces around a variable name and around a value.
Console.WriteLine($"{{x}} is {x}");
Console.WriteLine($"{{{x}}}");
The {{ and }} sequences produce single braces. In
{{{x}}}, the outer pairs are literal braces and the inner pair is
an interpolation hole.
Console.WriteLine($@"{path}\Documents");
The $@ prefix creates an interpolated verbatim string, where
backslashes are not escape characters. The order of $ and
@ does not matter.
$ dotnet run
{x} is 5
{5}
C:\Users\Jan\Documents
C:\Users\Jan\Documents
Conditional operator
The colon in a hole starts the format string. A conditional operator, which also contains a colon, must therefore be enclosed in parentheses.
var items = new Dictionary<string, int>
{
["ring"] = 2,
["lamp"] = 1,
["chair"] = 3,
["coin"] = 5,
["pen"] = 1,
};
foreach (var (k, v) in items)
{
Console.WriteLine($"{v} {k}{(v == 1 ? "" : "s")}");
}
int stock = 0;
Console.WriteLine($"Status: {(stock > 0 ? "in stock" : "sold out")}");
We use the conditional operator for pluralization and for a status message.
Console.WriteLine($"{v} {k}{(v == 1 ? "" : "s")}");
Without the parentheses, the compiler reports error CS8361: a conditional expression cannot be used directly in a string interpolation, because the colon ends the interpolation.
$ dotnet run 2 rings 1 lamp 3 chairs 5 coins 1 pen Status: sold out
Expressions and method calls
Holes can contain arithmetic, method calls, indexers, lambda expressions, and operators.
int x = 5;
int y = 10;
Console.WriteLine($"The sum of {x} and {y} is {x + y}");
Console.WriteLine($"Max: {Math.Max(x, y)}, power: {Math.Pow(x, 3)}");
List<string> fruits = ["apple", "banana", "orange"];
Console.WriteLine($"Fruits: {string.Join(", ", fruits)}");
Console.WriteLine($"Count: {fruits.Count}, first: {fruits[0].ToUpper()}");
Console.WriteLine($"Longest: {fruits.MaxBy(f => f.Length)}");
string? nick = null;
Console.WriteLine($"Nick: '{nick}', or default: '{nick ?? "none"}'");
We insert computed values, collection data, and a nullable string.
Console.WriteLine($"Longest: {fruits.MaxBy(f => f.Length)}");
The MaxBy method with a lambda expression returns the longest
fruit name.
Console.WriteLine($"Nick: '{nick}', or default: '{nick ?? "none"}'");
A null value is inserted as an empty string. The null-coalescing
operator provides a default.
$ dotnet run The sum of 5 and 10 is 15 Max: 10, power: 125 Fruits: apple, banana, orange Count: 3, first: APPLE Longest: banana Nick: '', or default: 'none'
Newlines in interpolation holes
Since C# 11, the expressions in holes can span multiple lines. This helps with long LINQ queries.
List<User> users =
[
new("John", "Doe", 1230),
new("Lucy", "Novak", 670),
new("Robin", "Brown", 2300),
new("Amy", "Doe", 1250),
];
Console.WriteLine($"Highest salary: {
users.MaxBy(u => u.Salary)
}");
Console.WriteLine($"Salaries over 1000: {
string.Join(", ", users
.Where(u => u.Salary > 1000)
.Select(u => u.FirstName))
}");
record User(string FirstName, string LastName, int Salary);
We embed two LINQ queries in interpolated strings.
Console.WriteLine($"Salaries over 1000: {
string.Join(", ", users
.Where(u => u.Salary > 1000)
.Select(u => u.FirstName))
}");
The newlines are part of the C# expression, not of the resulting string.
$ dotnet run
Highest salary: User { FirstName = Robin, LastName = Brown, Salary = 2300 }
Salaries over 1000: John, Robin, Amy
Raw interpolated strings
Raw string literals, introduced in C# 11, start and end with at least three double quotes. They may contain quotes and backslashes without escaping. A multiline raw string starts on the line after the opening quotes, and the indentation of the closing quotes is removed from all lines.
var countries = new Dictionary<string, string>
{
["Slovakia"] = "Bratislava",
["Germany"] = "Berlin",
["Hungary"] = "Budapest",
};
foreach (var (k, v) in countries)
{
Console.WriteLine($"""The capital of "{k}" is "{v}".""");
}
string name = "Alice";
int score = 95;
string message = $"""
Dear {name},
your score is {score}.
{(score >= 90 ? "Excellent work!" : "Keep practicing!")}
""";
Console.WriteLine(message);
We print quoted text and a multiline message.
Console.WriteLine($"""The capital of "{k}" is "{v}".""");
The double quotes around the names need no escaping.
string message = $"""
Dear {name},
your score is {score}.
{(score >= 90 ? "Excellent work!" : "Keep practicing!")}
""";
The four spaces before the closing quotes are removed from each line, so the message starts at the first column.
$ dotnet run The capital of "Slovakia" is "Bratislava". The capital of "Germany" is "Berlin". The capital of "Hungary" is "Budapest". Dear Alice, your score is 95. Excellent work!
Literal braces in raw strings
In a raw interpolated string, the number of $ characters gives
the number of braces that open a hole. With $$, single braces are
literal text and holes use double braces. This is convenient for JSON, CSS, or
code templates.
string name = "Alice";
int age = 28;
string[] langs = ["C#", "F#"];
string json = $$"""
{
"name": "{{name}}",
"age": {{age}},
"languages": [{{string.Join(", ", langs.Select(l => $"\"{l}\""))}}]
}
""";
Console.WriteLine(json);
We build a JSON document with a raw interpolated string.
"name": "{{name}}",
The single braces of the JSON object stay in the output, while
{{name}} inserts the variable.
"languages": [{{string.Join(", ", langs.Select(l => $"\"{l}\""))}}]
A hole can contain another interpolated string. Here, each language is enclosed in quotes. For real applications, a JSON serializer is safer, because it escapes special characters.
$ dotnet run
{
"name": "Alice",
"age": 28,
"languages": ["C#", "F#"]
}
Culture-specific formatting
By default, an interpolated string formats values with the current culture.
The string.Create method and the FormattableString
type let us choose a culture explicitly.
using System.Globalization;
double price = 1234.5;
var dt = new DateTime(2026, 11, 6);
Console.WriteLine(CultureInfo.CurrentCulture.Name);
Console.WriteLine($"{price:N2} {dt:d}");
var de = new CultureInfo("de-DE");
var sk = new CultureInfo("sk-SK");
Console.WriteLine(string.Create(de, $"{price:N2} {dt:d}"));
Console.WriteLine(string.Create(sk, $"{price:C2} {dt:D}"));
string data = string.Create(CultureInfo.InvariantCulture, $"{price},{dt:yyyy-MM-dd}");
Console.WriteLine(data);
FormattableString fs = $"{price:N2} on {dt:d}";
Console.WriteLine(fs.Format);
Console.WriteLine(fs.ToString(de));
Console.WriteLine(FormattableString.Invariant(fs));
We format a number and a date with the current, German, Slovak, and invariant cultures.
Console.WriteLine(string.Create(de, $"{price:N2} {dt:d}"));
The string.Create(IFormatProvider, ...) overload formats the
interpolated string with the given culture. Germans use a dot to group digits
and a comma as the decimal separator.
string data = string.Create(CultureInfo.InvariantCulture, $"{price},{dt:yyyy-MM-dd}");
Data written to files or sent to other programs should be formatted with the invariant culture, so that it can be read back on any machine.
FormattableString fs = $"{price:N2} on {dt:d}";
When an interpolated string is assigned to a FormattableString,
the compiler keeps the format and the arguments instead of producing a string.
The Format property shows the composite format;
ToString(IFormatProvider) and
FormattableString.Invariant format it with a chosen culture.
$ dotnet run
en-US
1,234.50 11/6/2026
1.234,50 06.11.2026
1 234,50 € piatok 6. novembra 2026
1234.5,2026-11-06
{0:N2} on {1:d}
1.234,50 on 06.11.2026
1,234.50 on 11/06/2026
Constant interpolated strings
Since C# 10, an interpolated string can be a constant if all its holes are constant strings.
const string Product = "Zetcode";
const string Version = "2.1";
const string Title = $"{Product} {Version}";
Console.WriteLine(Title);
Greet(Title);
void Greet(string app, string text = $"Welcome to {Product}")
{
Console.WriteLine($"{app}: {text}");
}
We build a constant title and use a constant interpolated string as a default parameter value.
const string Title = $"{Product} {Version}";
The string is evaluated by the compiler. Constant interpolated strings can
also be used in attributes and switch case labels. Numbers are not
allowed in such holes, because their formatting depends on the culture.
$ dotnet run Zetcode 2.1 Zetcode 2.1: Welcome to Zetcode
Source
In this article we have built strings with string interpolation in C#.
Author
List all C# tutorials.