Perform Basic String Formatting in C#
Learn how to use interpolated strings in C# to format output in a clean and readable way.
Question
Which of the following lines of code correctly uses string interpolation assuming that the variable
value
is a string?
Try to answer this question first on freeCodeCamp .
Option 1
Console.WriteLine(@"My value: {value}");
The @
symbol indicates a
verbatim string
, which means any content inside the string is treated literally.
Output:
My value: {value}
Incorrect - this does not perform string interpolation.
Option 2
Console.WriteLine($"My value: {value}");
The $
symbol indicates this is an
interpolated string
. Expressions inside {}
are evaluated and inserted into the string.
Assuming value = "The value"
, the output would be:
My value: The value
Correct - this is an example of string interpolation in C#.
Option 3
Console.WriteLine(@"My value: [value]");
Again, this is a
verbatim string
like in option 1. The brackets []
are not used for interpolation in C#. Everything inside is printed exactly as written.
Output:
My value: [value]
Incorrect – this does not use interpolation.