CSharp - String String interpolation


A string preceded with the $ character is called an interpolated string.

Interpolated strings can include expressions inside braces:

int x = 4;
$"A square has {x} sides"  // A square has 4 sides

C# will convert the expression to a string by calling its ToString method.

You can change the formatting by appending the expression with a colon and a format string:

string s = $"255 in hex is {byte.MaxValue:X2}";  
// X2 means 2-digit Hexadecimal
// "255 in hex is FF"

To use multi line interpolated strings, specify the verbatim string operator.

$ operator must come before @:

int x = 2;
string s = $@"this spans {
x} lines";

To include a brace literal in an interpolated string, repeat the desired brace character.