C# 6 Features: String Interpolation

by Joe on Jan 29th in .Net, C#, Visual Studio

I had a few minutes, so I thought I’d get a series of posts started – really quick snippets about why C# 6 features are interesting, and why they matter.

The one I’m going to start with is the one I’ve been using far and away the most. String Interpolation.

Take a look at this:

It’s pretty basic. We’re instantiating a Person (remember him, from our last post?) and showing the properties in the console window. Nothing fancy.

In prior to C# 6, this involved either using String.Format() or, if you were really crazy doing something like this:

Now, however, we have something new. String interpolation!

By just putting a Dollar Sign “$” in front of the string, we can insert adhoc bits of code into the string.

This can be dangerous. I could see it leading to some funky code.

As with so much in life, with great power comes great responsibility…

Take a look at how it ends up with our simple example.

Other Posts in the Series

5 Comments

  1. Andrew Siemer

    29th January 2016

    Its like little razor templates built into the framework…everywhere! Awesome.

    • Joe

      29th January 2016

      I know, right? Mostly, though, I think it just makes things a lot more readable. Even in a short, simple example, the intent is much more clear in the third snippet than in either of the first two snippets. In anything more complex, there’s no hope of understanding a long String.Format expression.

  2. Mark Reynolds

    30th January 2016

    It works great! I’ve already used deployed an application using it.

    • Joe

      31st January 2016

      Awesome! Are you using any of the other new C# features? Auto-Property Initialization perhaps?

  3. Justin Self

    1st February 2016

    It works… LIKE A BOSS!

Trackbacks/Pingbacks

  1. Dew Drop – February 1, 2016 (#2178) | Morning Dew

Leave a Reply

Powered By Wordpress Designed By Ridgey