I'm a beginner to C#. So far I came across several ways that I can use to embed variables in a string value. One of the is String Interpolation which was introduced in C# 6.0. Following code is an example for String Interpolation.
int number = 5;
string myString = $"The number is {number}";
What I want to know is whether there is a benefit of using String Interpolation over the following ways to format a string.
// first way
int number = 5;
string myString = "The number is " + number;
//second way
int number = 5;
string myString = string.Format("The number is {0}", number);
The first way that you have shown will create multiple strings in memory. From memory I think it creates the number.ToString()
string, the literal "The number is "
string and then the string with name myString
For the second way that you show it's very simple: String interpolation compiles to the string.Format()
method call that you use.
EDIT: The second way and the interpolation will also support format specifiers.
A more detailed discussion by Jon Skeet can be found here: http://freecontent.manning.com/interpolated-string-literals-in-c/