C# 6.0 String Interpolation

C# 6.0 arrived with new wonderful features and they will change the way you write C#. Let’s get into one of those and see how to use it.

When you build a string, usually you use the String.Format method, the concatenation is more efficient and it’s not as complex as using the StringBuilder, However you may think you can argue there are some times is better to use StringBuilder, like when you are building a really long string for example, another way for relativily simple strings or even medium size strings the Format method is the best choice.

First of all, for the demo we are going to build a string like the normal way we use to make with the String.Format method. Also, two variables to use with it.

method

Ok, it is quite easy, we basically supply the parameters that the first string parameter asks wherever there is a curly brace pattern like {someNumber} appears, so we can match up the parameter with their values in one simple way.

But after all this is neither a complex one string nor a long one string, things may get a little bit confusing with one of these.

So with a larger string with many more values, it could be easier to match up the wrong value with the parameter and it can be less readable.

Unfortunately, common tools like Visual Studio doesn’t have any feature to highlighting the placeholder with the value. However, if you use Resharper, it adds this functionality.

When it comes with c# 6.0 we won’t even really need that type of feature any longer, because we have a new feature that allow us to format a string by using the actual variables themselves within the String.Format method. So let’s rewrite the assigning of the message variable and see how it looks like:

message variable

We begin our string with a dollar symbol which says to the compiler it will be a formatted string, then into the quotes we pass the actual values within the curly braces, thus Visual Studio recognizes these variables inside the string. The highlight feature works as normally it does with the scope variables highlighting feature, cool! Isn’t it?

Since this feature looks for the values in the context, no matter if we have an anonymous object instead those two variables. The code will work this way.

variables

Another great advantage with this new feature is that we won’t lose the formatting options that we might normally have. For instance, to format a s=date we will do the following:

formatting

The value of the stringDate variable would be “Showing current date 20151006”. Doing this with c# 6.0 would be.

Code

And it will give us the same thing. Therefore basically anything we can do with String.Format method we will be able to do it with the dollar symbol operator that provide the new wonderful feature of c# 6.0 a very useful and easy feature to use.


Similar Articles