C # - string interpolation
I am starting with C #. So far, I have come across several ways that I can use to insert variables into a string value. One of the string interpolations introduced in C # 6.0. The following code is an example for string interpolation.
int number = 5;
string myString = $"The number is {number}";
I want to know if it is possible to use String Interpolation for the following ways of formatting 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);
source to share
The first way you provided will create multiple lines in memory. From memory I think it creates a string number.ToString()
, literal "The number is "
and then a string namedmyString
For the second way you show it is very simple: String interpolation is compiled when you call the method string.Format()
you are using.
EDIT . The second way and 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/
source to share