C# String Interpolation

String interpolation is a feature in C# that allows you to embed expressions into string literals. This makes it easier to build dynamic strings and templates with placeholders. String interpolation is supported in C# 6.0 and later versions.

To use string interpolation, you start with a string literal that contains placeholders for values that you want to insert. You then use the ${} syntax to enclose expressions that evaluate to the values you want to insert. The result is a string that replaces the placeholders with the evaluated expressions.

Here is an example:

1int age = 22; 2string name = "Bob"; 3string message = $"My name is {name} and I am {age} years old."; 4 5Console.WriteLine(message);

Output: My name is Bob and I am 22 years old.

In this example, we define two variables age and name, and use them in a string interpolation expression to create a message string. The ${} syntax is used to embed the expressions that evaluate to the variable values, and the resulting string is assigned to the message variable.

You can also use string interpolation with methods and other expressions. For example:

1int x = 5; 2int y = 7; 3string result = $"The sum of {x} and {y} is {x + y}."; 4 5Console.WriteLine(result);

Output: The sum of 5 and 7 is 12.

In this example, we use the string interpolation feature to embed the expression x + y in a string literal.

You can also use string interpolation to format values using format specifiers. For example:

1double price = 10.99; 2int quantity = 3; 3string result = $"The total cost is {price * quantity:C2}."; 4 5Console.WriteLine(result);

Output: The total cost is $32.97.

In this example, we use the format specifier :C2 to format the product of price and quantity as a currency value with two decimal places.

String interpolation provides a convenient way to build dynamic strings and templates with placeholders. It simplifies the code and makes it more readable by allowing you to embed expressions directly in string literals.