C# String Interpolation

String interpolation allows you to insert variables and expressions directly into a string using curly braces ({ }). This makes the code more readable and maintainable compared to concatenation.

Key Topics

1. Basic String Interpolation

Example: Simple Interpolation

string name = "Alice";
int age = 30;
string message = $"Name: {name}, Age: {age}";
Console.WriteLine(message);  // Outputs: Name: Alice, Age: 30

2. Interpolating Expressions

Example: Interpolating Calculations

int a = 5;
int b = 10;
Console.WriteLine($"Sum: {a + b}");  // Outputs: Sum: 15

3. Using Format Specifiers

Example: Formatting Numbers

double price = 123.456;
Console.WriteLine($"Price: {price:C2}");  // Outputs: Price: $123.46

Key Takeaways

  • Use $"" to start an interpolated string.
  • Place variables or expressions inside { } within the string.
  • Format specifiers can be used to format the output.