Karl Gjertsen

Architect, Developer, Speaker, Bad Golfer,
Raygun brand ambassador and creator of Infiniforms

String Interpolation in C# 6

Unlike some of the previous releases C# 6.0 isn’t a radical change from the current version of C#. But, it may still change the way you write code. A great example of this is String Interpolation.

We originally started concatenating strings using the plus symbol:

var myClass = new MyClass();

var fullName = "Full name: " + myClass.FirstName + myClass.LastName;

We then moved on to using String.Format:

var myClass = new MyClass();

var fullName = String.Format("full name: {0} {1}", myClass.FirstName, myClass.LastName);

Now, C# 6.0 gives us a new way to accomplish the same task. Using this is straight forward. The string is prefixed with a $ symbol and the values we want to be added are wrapped in curly braces:

var myClass = new MyClass();

var fullName = $"full name: {myClass.FirstName} {myClass.LastName}";

You can also apply formatting to a value in the curly braces:

var hours = $"Hours: {time:hh}";
%d bloggers like this: