String interpolation
Learn to embed variables in text with $"...".
String interpolation
The modern way to embed variables into text is string interpolation. You start the string with a $ prefix and put the variable inside curly braces { }: $"Hello, {name}!".
Without the $ sign, the curly braces are ordinary characters and you would see the variable name, not its value. $"Price: {price} USD" becomes Price: 25 USD. No need for the + operator in between.
Expressions and formatting
Inside the curly braces you can write expressions, not only variables: $"Total: {price * quantity} USD". You can also add a colon for formatting: $"Year: {now:yyyy}" prints just the year.
Formatting controls how numbers and dates look. For example, {price:F2} shows the price with two decimal places. Interpolation thus gives you both value and presentation in one spot.
Exercise Write a greeting message
Declare a name variable with the value "Alex". Then use interpolation to produce "Hello, Alex!" with Console.WriteLine. You must use the $ prefix and {name}.
Show example solution
Write string name = "Alex";, then Console.WriteLine($"Hello, {name}!");
Example solution:
using System;
class Program
{
static void Main()
{
string name = "Alex";
Console.WriteLine($"Hello, {name}!");
}
}
Test yourself
-
Write the interpolation prefix
string name = "Alex"; string greeting = ____ "Hello, {name}!";Show answer
string name = "Alex"; string greeting = $ "Hello, {name}!"; -
With string name = "Sam"; what does $"Hello, {name}!" print?
string name = "Sam"; Console.WriteLine($"Hello, {name}!");- Hello, {name}!
- Hello, Sam
- Hello, name!
- Hello, Sam!
Show answer
Hello, Sam! — Correct. {name} is replaced by the value and the exclamation stays.
-
Match each expression to its output
- $"{5+3}"
- 8
- $"{5*3}"
- 15
- $"{5-3}"
- 2
- $"{10/2}"
- 5