What is String Interpolation in C# and How to Use It
string interpolation is a way to insert variables or expressions directly inside a string by prefixing the string with $ and placing the variables inside curly braces {}. It makes building strings easier and more readable compared to older methods like concatenation or String.Format.How It Works
String interpolation in C# works by letting you write a string that contains placeholders for variables or expressions. You start the string with a $ sign, then put the variable names or expressions inside curly braces {}. When the program runs, it replaces those placeholders with the actual values.
Think of it like filling in blanks on a form. Instead of writing the whole sentence and then adding pieces together, you write the sentence with blanks that get filled automatically. This makes your code cleaner and easier to understand.
Example
This example shows how to use string interpolation to include a name and age inside a greeting message.
string name = "Alice"; int age = 30; string message = $"Hello, my name is {name} and I am {age} years old."; System.Console.WriteLine(message);
When to Use
Use string interpolation whenever you need to create strings that include variable values or expressions. It is especially helpful for building messages, logs, or any text output that changes based on data.
For example, you might use it to show user information, format dates, or display calculated results. It makes your code shorter and easier to read compared to older ways like concatenation or String.Format.
Key Points
- String interpolation uses
$"...{variable}..."syntax. - It replaces placeholders with actual values at runtime.
- Makes code more readable and concise than concatenation.
- Supports expressions inside the curly braces, not just variables.
- Introduced in C# 6.0 and is now the preferred way to format strings.