In C#, string interpolation lets you put variables and expressions straight inside a string. You start the string with $ and wrap each value in curly braces.
It is a short, readable alternative to string.Format() and to joining pieces with +.
Syntax
Add $ before the quote, then use braces for values.
C#
string name = "Sam";
string message = $"Hi {name}";
Put it right before the opening quote. It turns the text into an interpolated string.
{name}
A hole. Any variable or expression inside the braces is replaced by its value.
{value:F2}
A format specifier after a colon. F2 means two decimal places.
{value,8}
Alignment after a comma. Pads the value to a width of 8 characters.
{{ and }}
Print a literal { or }.
C# Examples
Example 1 — Basic Interpolation
Put a name and an age into one sentence.
C#
using System;
class Program {
static void Main() {
string name = "Sam";
int age = 20;
Console.WriteLine($"Hi {name}, you are {age} years old.");
}
}
Output
Hi Sam, you are 20 years old.
How It Works
Start with $. It marks the string as interpolated.
Use braces.{name} and {age} are replaced by their values.
No + needed. You do not have to join text and numbers by hand.
Example 2 — Format Specifiers
Add a colon and a format code to control how a number looks. This output assumes an English (US) culture.
C#
using System;
class Program {
static void Main() {
double price = 4.5;
int id = 7;
Console.WriteLine($"Price: {price:F2}");
Console.WriteLine($"Item: {id:D3}");
}
}
Output
Price: 4.50
Item: 007
How It Works
F2. Fixed-point with two digits after the decimal point.
D3. A whole number padded with zeros to three digits.
Colon starts the format. Everything after it is the format code.
Example 3 — Expressions and Literal Braces
A hole can hold a calculation. Double the braces when you want to print them.
C#
using System;
class Program {
static void Main() {
int a = 3;
int b = 4;
Console.WriteLine($"{a} + {b} = {a + b}");
Console.WriteLine($"{{a}} is {a}");
Console.WriteLine($"Bigger? {(a > b ? "a" : "b")}");
}
}
Output
3 + 4 = 7
{a} is 3
Bigger? b
How It Works
Math inside braces.{a + b} is calculated first, then printed.
Double braces.{{a}} prints the text {a}.
Parentheses for ?:. The colon of the conditional would otherwise look like a format code.
Frequently Asked Questions
It is a way to insert variables and expressions into a string using $"...{value}...".
Double it. Write {{ to print { and }} to print }.
Add a colon and a format code, such as {price:F2} for two decimal places.
It does the same job and is usually easier to read because values sit right where they appear.
Yes, but wrap it in parentheses, like {(a > b ? "yes" : "no")}.