Edit

Share via

Use string interpolation to construct formatted strings

Create an interpolated string

Run the following code in the interactive window. Select the Enter focus mode button. Then, type the following code block in the interactive window (replace <name> with your name) and select Run:

var name = "<name>";
Console.WriteLine($"Hello, {name}. It's a pleasure to meet you!");

When you run the code, Output displays a string that includes your name in the greeting. The string argument of the WriteLine method call is an interpolated string expression. It's a kind of template that lets you construct a single string (called the result string) from a string that includes embedded code. Interpolated string expressions are particularly useful for inserting values into a string or concatenating (joining together) several strings.

The example above contains the two elements that every interpolated string expression must have:

  • A string literal that begins with the $ character before its opening quotation mark character. There can't be any spaces between the $ symbol and the quotation mark character. (If you'd like to see what happens if you include one, insert a space after the $ character in the interactive window and run the updated code. The C# compiler complains, "Unexpected character '$'".)

  • One or more interpolation expressions. An interpolation expression is indicated by an opening and closing brace ({ and }). You can put any C# expression that returns a value (including null) inside the braces.

Let's try a few more string interpolation examples with some other data types.

Try the code in your browser