String interpolation is a syntactic shorthand for the string.Format()
introduced in C# 6.
var name = "World";
var oldWay = string.Format("Hello, {0}!", name); // returns "Hello, World"
var newWay = $"Hello, {name}!"; // returns "Hello, World"
var name = "World";
var str = $"Hello, {name}!";
//str now contains: "Hello, World!";
Internally this
$"Hello, {name}!"
Will be compiled to something like this:
string.Format("Hello, {0}!", name);
You can use a colon and the standard numeric format syntax to control how numbers are formatted.
var decimalValue = 120.5;
var asCurrency = $"It costs {decimalValue:C}";
// String value is "It costs $120.50" (depending on your local currency settings)
var withThreeDecimalPlaces = $"Exactly {decimalValue:F3}";
// String value is "Exactly 120.500"
var integerValue = 57;
var prefixedIfNecessary = $"{integerValue:D5}";
// String value is "00057"
var date = new DateTime(2015, 11, 11);
var str = $"It's {date:MMMM d, yyyy}, make a wish!";
System.Console.WriteLine(str);
You can also use the [DateTime.ToString](<https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx>)
method to format the DateTime
object. This will produce the same output as the code above.
var date = new DateTime(2015, 11, 11);
var str = date.ToString("MMMM d, yyyy");
str = "It's " + str + ", make a wish!";
Console.WriteLine(str);
Output:
It’s November 11, 2015, make a wish!