C# String Interpolation
String interpolation is a cleaner, modern way to build text that mixes fixed words with variable values. Instead of chaining pieces with the + operator, you drop variables straight into the string.
The $ Symbol
To create an interpolated string, put a dollar sign ($) directly before the opening quote. Inside the string you can then place any variable or expression inside curly braces { }, and C# replaces it with its value when the program runs.
Basic interpolation
string name = "Sofia";
int age = 28;
Console.WriteLine($"My name is {name} and I am {age} years old.");
// My name is Sofia and I am 28 years old.Why Interpolation Is Easier to Read
Compare interpolation to plain concatenation. The interpolated version keeps the words and values in a natural reading order, with no scattered quotes and plus signs, which makes long messages far easier to write and to fix later.
Same result, two styles
string city = "Paris";
// Concatenation
Console.WriteLine("Welcome to " + city + "!");
// Interpolation (clearer)
Console.WriteLine($"Welcome to {city}!");Expressions Inside the Braces
The braces are not limited to plain variables. You can put a calculation or a method call inside them, and C# evaluates it first, then inserts the result into the text.
Calculations in a string
int price = 20;
int quantity = 3;
Console.WriteLine($"The total is {price * quantity} dollars.");
// The total is 60 dollars.- Start the string with $ before the opening quote.
- Put variables or expressions inside { and }.
- You can combine $ with @ (as $@"...") to build multi-line interpolated text.