C# ยท Chapter 13 of 46

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.

Syntax
$"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.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    string name = "Amy";
    int age = 25;
    Console.WriteLine($"Hello, {name}! You are {age} years old.");
  }
}
Output
Hello, Amy! You are 25 years old.

The variables name and age are inserted directly into the string.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    double price = 9.5;
    Console.WriteLine($"Total: {price:F2}");
  }
}
Output
Total: 9.50

The :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.
๐Ÿ’ก Note: String interpolation is the preferred modern way to build strings with embedded values in C#.

๐Ÿ“ Quick Quiz

1. Which symbol marks an interpolated string?

2. Where do you place a variable inside an interpolated string?

3. What does {price:F2} do?