Perform Basic String Formatting in C#

Learn about interpolated strings in c# and how to use them to format strings.

Question

Which of the following lines of code correctly uses string interpolation assuming that the variable value is a string?

Option 1

Console.WriteLine(@"My value: {value}");

The @ character at the start of the string indicates this is a verbatim string. This means anything inside the string is interpreted literally.

So the command above would write My value: {value} to the console.

This is incorrect.

Option 2

Console.WriteLine($"My value: {value}");

The $ character at the start of the string indicates this is an interpolated string. When an interpolated string is processed into the final string, the compiler will replace anything inside {} with the result of the expression.

Let’s say we have set the value of value to "The value". The command above would write My value: The value to the console.

This is correct.

Option 3

Console.WriteLine(@"My value: [value]");

The @ character at the start of the string indicates this is a verbatim string. This means anything inside the string is interpreted literally.

So the command above would write My value: [value] to the console.

This is incorrect.