C# 6 String Interpolation

C# 6 String Interpolation

String Interpolation is a new feature in C# 6. It's a nice alternative to string cocatenation using "+" or string.format. One can now use expressions within strings and specify you are using string interpolation by prefixing the string with a $ symbol.

String.Format in C#

Before string interpolation in C# 6 you probably used string.format. It might look something like this using Console.WriteLine.

var firstname = "David";
var lastname = "Hayden";

Console.WriteLine("{0} {1} was here.", firstname, lastname);

This is still an acceptable way to display a formatted string, but string interpolation makes it so much clearer.

String Interpolation in C# 6

We can write that same lines of code using string interpolation in C# 6.

var firstname = "David";
var lastname = "Hayden";

Console.WriteLine($"{firstname} {lastname} was here.");

Notice the $ symbol before the string and the brackets around firstname and lastname.

Here is another example where we display the firstname and lastname from properties in an anonymous type.

var person = new { Firstname = "David", Lastname = "Hayden" };

Console.WriteLine($"{person.Firstname} {person.Lastname} was here.");

Add some formatting when you just want to display the name of the day given the current datetime.

Console.WriteLine($"Today is {DateTime.Now:dddd}.");

Or, perhaps you want to display PI to 2 decimal places and right-aligned within a space of 10 characters.

Console.WriteLine($"PI = {Math.PI,10:N}");

Very cool! Check out another C# 6 feature: C# 6 Auto-Property Initializers.