One of the top ten requests on uservoice is String Interpolation. Today we are going to see how to use this feature and how it is implemented in C# 6.0.
We all use similar expressions:
var str = string.Format("Date: {0}", DateTime.Now);
This is string interpolation in C# before 6.0.
Now, in C# 6.0, we have new string interpolation technique:
var str = $"Date: {DateTime.Now}";
There was nothing new added in to runtime, this is just a syntaxis sugar for "old shcool" interpolation. C# compiler will convert new expression in to "old" one during compilation.
Let's check out more examples:
static void Main(string[] args)
{
Console.WriteLine($"test {10}");
//string.Format("test {0}", 10);
var a = 1.2345;
Console.WriteLine($"test {a}");
//string.Format("test {0}", a);
Console.WriteLine($"test {a} {a} {a}");
//string.Format("test {0} {1} {2}", a, a, a);
Console.WriteLine($"test {a + 10}");
//string.Format("test {0}", a + 10);
Console.WriteLine($"test {a:00.00}");
//string.Format("test {0:00.00}", a);
Console.WriteLine($"test {a + 10:F2}");
//string.Format("test {0:F2}", a + 10);
Console.WriteLine($"test {Get10():F2}, {Get0()}");
//string.Format("test {0:F2}, {1}", Get10(), Get0());
Console.WriteLine($"test {(args.Length != 0 ? "0" : "1")}");
//string.Format("test {0}", (args.Length != 0 ? "0" : "1"));
Console.WriteLine($"test {(args.Length == 0 ? Get0() : "1")}");
// string.Format("test {0}", (args.Length == 0 ? Get0() : "1"));
}
private static string Get0()
{
return "0";
}
private static double Get10()
{
return 876.543;
}
We can check IL code to be shure that this is just a syntax sugar. IL code for first example:
IL_0000: nop
IL_0001: ldstr "Date: {0}"
IL_0006: call valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
IL_000b: box [mscorlib]System.DateTime
IL_0010: call string [mscorlib]System.String::Format(string, object)
As you can see in line IL_0010, there was just a String.Format call.