String interpolation allows the developer to combine variables
and text to form a string.
Two int
variables are created: foo
and bar
.
int foo = 34;
int bar = 42;
string resultString = $"The foo is {foo}, and the bar is {bar}.";
Console.WriteLine(resultString);
Output:
The foo is 34, and the bar is 42.
Braces within strings can still be used, like this:
var foo = 34;
var bar = 42;
// String interpolation notation (new style)
Console.WriteLine($"The foo is {{foo}}, and the bar is {{bar}}.");
This produces the following output:
The foo is {foo}, and the bar is {bar}.
Using @
before the string will cause the string to be interpreted verbatim. So, e.g. Unicode characters or line breaks will stay exactly as they’ve been typed. However, this will not effect the expressions in an interpolated string as shown in the following example:Console.WriteLine($@“In case it wasn’t clear: \u00B9 The foo is {foo}, and the bar is {bar}.”); Output:
In case it wasn’t clear:
\u00B9
The foo
is 34,
and the bar
is 42.