Compile and run
Learn to compile and run a C# program with dotnet run and dotnet build.
String interpolation
String interpolation is a way to embed a variable or expression inside text. You start the string with the $ sign and put the expression you want to embed inside curly braces { }.
string name = "Alex";
Console.WriteLine($"Hello, {name}!");The {name} expression is replaced by the variable's value. Output: Hello, Alex! This is more readable than concatenating strings.
The string variable
To store text for later use you declare a string variable. A variable holds a value and lets you reuse it any time.
string name = "Alex";Here name is the variable's name and "Alex" is the value it holds. Variable names use English letters and start with lowercase. You can change the value later.
Exercise Print a message with interpolation
Declare a string name variable (example: "Alex") and print Hello, Alex! using string interpolation with Console.WriteLine.
Show example solution
First write string name = "Alex";, then Console.WriteLine($"Hello, {name}!");.
Example solution:
using System;
class Program
{
static void Main()
{
// Define a string variable
string name = "Alex";
// Print the message with interpolation
Console.WriteLine($"Hello, {name}!");
}
}
Test yourself
-
Which is a valid interpolated string?
- Console.WriteLine("Hello");
- Console.WriteLine($"Hello, {name}!");
- Console.WriteLine("Hello, {name}!");
- Console.WriteLine(Hello, {name}!);
Show answer
Console.WriteLine($"Hello, {name}!"); — Correct! The $ prefix marks interpolation and {name} is embedded.
-
Interpolation prefix
Console.WriteLine(____"Hello, {name}!");Show answer
Console.WriteLine($"Hello, {name}!"); -
Match the interpolation concepts
- $
- Interpolation prefix
- { }
- Embedding expression
- string
- Variable type
- WriteLine
- Output method