C# 6 features – String interpolation 1


This article is part of series about C# 6 features. Let focus on string interpolation this time. It’s one of the new C# features that will for sure affect the way you write C# code.

We used to appreciate string.Format method to construct strings. The method is very helpful but it’s usage is a bit tricky. One have to use numbered placeholders in the format string which must line up with separately specified arguments.

var msg = string.Format("{0} {1} is {2} year{{s}} old", firstName, lastName, age);

String interpolation introduces a new way of getting the same string in much easier to read form. You can just put expressions directly in string literal.

var msg = $"{firstName} {lastName} is {age} year{{s}} old";

Please note that interpolated string starts with $ .Additionally, you can add formatting as in string.Format.

var msg = $"{firstName} {lastName} is {age:D3} year{{s}} old";

The contents of the holes can be pretty much any expression, including even other strings:

var msg = $"{firstName} {lastName} is {age:D3} year{(age == 1 ? "" : "s")} old";

Please note that the conditional expression is parenthesized –   would get confused as the ending of the interpolated string.


How string interpolation works?

Some of you might want to know how it is implemented.  So, interpolated strings are transformed at compile time to equivalent string.Format calls.

// Following:

var msg = $"{firstName} {lastName} is {age:D3} year{(age == 1 ? "" : "s")} old";

// Will become:

object[] args = new object[] { firstName, lastName, age, (age == 1 ? "" : "s") };
msg = string.Format("{0} {1} is {2:D3} year{3} old", args);


To sum up, string interpolation makes code much more easy to read. Which is actually a good thing.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler, 2008



Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “C# 6 features – String interpolation