Adventures In String Concatenation - Introducing String Interpolation

C# 6 has been out for quite some time now and I thought I would write up a quick post on one of its newer features, which I use quite often: string interpolation.

What is String Interpolation?

String Interpolation isn't really anything new per se, it just provides a way of building the strings in a somewhat readable fashion, devoid of endless trails of '+' characters and the indexed placeholders.

Let's take a look at few ways, where you might actually concatenate the strings and we can see, where the string interpolation might come in.

The Classic Approach: Concatenation

I'm sure, every developer who reads this article at one point or another has chained tons of strings together with the concatenation operator '+' , as shown below:

  1. string a = "Han";   
  2. string b = "shot";   
  3. string c = "first";   
  4. // Build your string  
  5. var sentence = a + " " + b + " " + c + ".";   
While this is fairly common, it is far from ideal. Concatenating a series of the strings like this can yield all sorts of an unexpected work for the compiler to do, but there really isn't anything wrong with it.

If you want to give the compiler a break and do some of the work yourself, you can use the String.Concat() method. This method accepts a set of parameters and does exactly, what you would imagine; it concatenates them efficiently:
  1. string a = "Han";   
  2. string b = "shot";   
  3. string c = "first";   
  4. // Build your string  
  5. var sentence = String.Concat(a," ",b," ",c,".");   
This gets a bit tricky, when you get into the loops as the compiler may not be able to perform as much optimization, as it would. This is where the StringBuilder class comes in. StringBuilders allow you to continually and efficiently build a string without generating potentially hundreds of individual strings to do so.

You would simply instantiate an instance of the StringBuilder class and then use the methods like Append() and AppendLine() to add to your string, until finally outputing your end result via a ToString() call:
  1. var sb = new StringBuilder();   
  2. for(var x = 1; x <= 5; x++)   
  3. {  
  4. sb.AppendLine(x);  
  5. }  
  6. var result = sb.ToString();   
  7. Even Better: Formatting  
Even Better: Formatting

In a scenario, we defined earlier, concatenation really isn't ideal. This is primarily true, because we have the values, which we are repeating (they are just spaces in this example, but they could not be) and are thus just wasting precious memory by defining them just to be concatenated.

The String.Format() method solves this issue by allowing us to build a "formatting string", which uses the Placeholders to define, where the additional parameters will be added to the string. It's not only more efficient than concatenating a large number of strings, but it can be quite readable as well:
  1. string a = "Han";   
  2. string b = "shot";   
  3. string c = "first";   
  4. // Build your string  
  5. var sentence = String.Format("{0} {1} {2}.",a,b,c);   
As you can see, this doesn't look like, but if we wanted to expand it a bit, you can see, how it might be more useful:
  1. var sentence = String.Format("{0} {1} {2}; {0} shot Greedo.",a,b,c);   
Meet String Interpolation

If there was any one of these options, which the String Interpolation feature is going to replace, it's going to be the String.Format() method. In fact, you can almost think of it, as a short-hand method for doing so.

The idea behind the string interpolation is that it removes the pesky placeholders, found in String.Format() calls and actually even removes any method calls. Roslyn compiler will do all of the work, when it recognizes, what is going on.

Let's take a look at our previous example again:
  1. var sentence = String.Format("{0} {1} {2}; {0} shot Greedo.",a,b,c);   
This would simply result in "Han shot first; Han shot Greedo.". Now, these Placeholders aren't exactly pleasing to the eye. Thus, let's replace this call with how it would be handled, using String Interpolation:
  1. var sentence = $"{a} {b} {c}; {a} shot Greedo.";   
That's it. Just append a '$' to the beginning of your string and include your variables within the Placeholders.

Roslyn will actually read the values and map the variable names to their appropriate Placeholders. Additionally, these same Placeholders will support all of the common formatting strings, which are used for DateTime or the numerical input as well :
  1. var date = new Date(1977,5,25);   
  2. var shooter = "Han";   
  3. var victim = "Greedo";   
  4. var shots = 42;   
  5. var sentence = $"{shooter} shot {victim} {shots} times on a {date:dddd}.";   
This would poutput "Han shot Greedo 42 times on a Wednesday". But string interpolation isn't limited just to your normal formatting strings, you can also use some logic :
  1. var sentence = $"{shooter} shot {victim} {(shots > 1 ? shots + " times" : "once")} on a {date:dddd}.";   
This would present the output "Han shot Greedo 42 times on a Wednesday", however, if you changed shots to 1, it would read "Han shot Greedo, once on a Wednesday".

Pretty neat.

It's not a hammer.

While this new feature is something which I found myself using more and more, it isn't an all-out replacement for some of the other approaches. All of the operators and methods, which were previously mentioned will work just fine and have their own strengths.

Personally, the most common uses for the string interpolation have been involving the entities or objects and referencing the properties of them, similar to :
  1. var widget = WidgetFactory.GenerateWidget();   
  2. Console.WriteLine($"Widget {widget.ID} was made on {widget.BuildDate}");   
The most important thing to take away from this is the following: do not to compromise the readability of your code over the things like the formatting strings. If you find a case, where this feature might be useful, take the advantage of it, but don't try to wedge it, especially for the sake of the readability.

More about Strings

If you want some extended reading on the strings in general, discussions on concatenation, performance and more, check out some of these resources,