String Interpolation in C# 6.0

C# 6.0 Features Series

String Interpolation is yet another feature in C# 6.0 that lets the users to concatenate two or more strings together . The String Interpolation is not just about string concatenation. In the previous versions of C# , we used the + operator to concatenate strings or use String.Format method which provides additional options to format the string. The String.Format is one of the useful method and most frequently used method for formatting the strings but sometimes it can be error prone considering the usage of the arguments {1} or the placeholders as shown below.

var str = String.Format("{0} is a {1}", "Senthil Kumar", "Programmer");

With String Interpolation , the developers can put the expressions directly in the string literal and display the value in a properly formatted way. You can apply different format specifiers like the way you do it for string.format method as well as specify conditions within the string literals. Below is a sample code snippet demonstrating the usage of the String Interpolation in C# 6.0

string name = "senthil";
int age = 18;            
var input = "{name} is { age : D3} years old";

No Responses

Leave a Reply