String Interpolation in C# 6.0

Up untill now we are using various options for formatting strings using String.Format or by concatenating string values using + operator or String.Concat function. 

In the case of using + operator , as the number of items that needs to concatenated increases it becomes very hard to maintain and to understand what we are doing and some times it may result in incorrect string ouput too.

This can be solved to some extent by using the String.Format function by using the literals as placeholders so that we will get to know what the output be in advance by looking at the text part. But here we may find problems if we don't give the parameter values in the same order as in the string text part. Also if the number of placeholders and the values in the parameter list are not in sync an exception will be thrown at runtime.

In C# 6.0, Microsoft added a new feature to make our life easier by allowing us to put the expressions directly in the string literal. Now we can inject the values into a string using curly bracket enclosed expressions.

To use this feature you will need to start the string with $ sign and then surround the expressions with curly braces in the string literal. Unlike placing positional indices in String.Format function, here we can introduce C# expressions itself inside the curly braces and during runtime it will be replaced with value and produces the text. Also we can insert expression of any type say int or double and the framework will internally call the toString method to produce the output without any errors.

Also we can use any valid C# expression inside the string literal and are not limited to only variables


No Comments

Add a Comment