We used to perform string interpolation,with string.Format() before C# 6.0. You may not have used it that much, but still it was complex to use, requiring you to match the exact variables name with the sequence to get expected output. Consider the listing below:
static void Main(string[] args)
{
string name = "ck";
int age = 30;
string message = string.Format("{0} is {1} years old", name, age);
string wrong_message = string.Format("{0} is {1} years old", age, name);
WriteLine(message);
WriteLine(wrong_message);
ReadKey(true);
}
As you notice in the above listing in the variable wrong_message, an unexpected value would get assigned because we have provided the wrong sequence of the variables. This is the problem with the string.format(). You will get output as shown below:
Output :
============
ck is 30 years old
30 is ck years old
============
In C# 6.0, string interpolation is much simpler. Using the $ now, string interpolation can be done as shown in the listing below:
static void Main(string[] args)
{
string name = "ck";
int age = 30;
string message = $"{name} is {age} years old";
WriteLine(message);
ReadKey(true);
}
As you see we are directly passing the variable name in the {}. This avoids the sequence problem of variables in string.format.
Note: Here I am using using static System.Console above the Main function, one the new feature of C# 6, thats why I am writting satement inside Main function directly WriteLine(message);
0 comments :
Post a Comment