String Interpolation is another feature, that ships with C# 6.0 and comes in handy when formatting and working with strings. There are a many ways to work with strings but generally when it comes down to formatting them, it is usually String.Format.

Here is an example from MSDN, showing the usual way of formatting strings using String.Format.

DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago"; 
int temp = -16; 
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.", dat, city, temp); 
Console.WriteLine(output); 
// The example displays the following output: 
    // At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.

This can become quite troublesome to work with when the string becomes long and has many arguments. It can also be difficult to maintain an overview of, due to the index based approach, as the order of the arguments might not necessarily appear in corresponding order in the string – no validation.

C# 6.0 – String Interpolation

This is what the above example looks like using String Interpolation.

DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago"; int temp = -16; 
string output = $"At {dat} in {city}, the temperature was {temp} degrees.";
Console.WriteLine(output); 
// The example displays the following output: 
    // At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.

This makes it easier to work with strings, as String Interpolation places the expressions directly in the string literal. It’s also much cleaner to work with and you simply prefix the string, with the dollar sign, to identify the string as interpolated. You can also still use format specificers and expressions as before, for example:

DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago"; 
int temp = -16; 
string output = $"At {dat} in {city}, the temperature was {temp > 9000 ? "hot" : "{temp}"} degrees.";

That’s it for now!