Brosteins

Developers, Technology Evangelists, Bros.

String Interpolation in C# 6

News about C# 6 has been out for quite a while, but I’m just getting around to playing with some of the new features of C# 6. Today, one of our summer interns was really excited about string interpolation in C# 6. Thanks to Jonathan Vanderford for inspiring me to share in his excitement!

Earlier in the summer, I spent a half-day working with our interns discussing good development techniques and general warning flags we often run into during code reviews. One of the topics we covered was string manipulation and concatenation. In our discussion we addressed bad string concatenation and good string concatenation techniques. For reference:

Poor String Concatenation Technique

Preferred String Concatenation Technique (using String.Format)

String Interpolation in C# 6 adjusts the preferred method for string concatenation. Instead of invoking String.Format, a “$” is placed in front of the string. For example:

Thinking back to String.Format, the values inside of the curly braces were placeholders, referring numerically to the additional argument indices. However, with the new $”” notation, values inside of the curly braces are actually expressions that are evaluated by the compiler and fed into String.Format.

Although this isn’t a revelation, it is a quick shortcut and tip that can make your code cleaner and more expressive. After all, our job as developers isn’t to write more code, but write code that is more readable by others. Readability leads to maintainability.

Share

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.