C# String Interpolation
String interpolation lets you embed variables and expressions directly inside a string using a $ prefix and curly braces {}. It is a cleaner alternative to concatenating strings with the + operator.
Interpolated strings can include not just variables but also expressions, method calls, and formatting, making output code much more readable.
$"text {variable} text"Basic interpolation
Prefix a string with $ and place variables inside curly braces, like `$"Hello, {name}"`. The variable's value is automatically inserted into the string.
Expressions and formatting
You can put any expression inside the braces, such as `{age + 1}`, and use format specifiers like `{price:C}` for currency or `{value:F2}` for two decimal places.
using System;
class Program {
static void Main() {
string name = "Amy";
int age = 25;
Console.WriteLine($"Hello, {name}! You are {age} years old.");
}
}Hello, Amy! You are 25 years old.The variables name and age are inserted directly into the string.
using System;
class Program {
static void Main() {
double price = 9.5;
Console.WriteLine($"Total: {price:F2}");
}
}Total: 9.50The :F2 format specifier displays the number with two decimal places.
Key points
- Interpolated strings start with a $ before the opening quote.
- Variables and expressions go inside curly braces {}.
- Format specifiers like :F2 control number formatting.
- Interpolation is more readable than manual string concatenation.
