Easy String Interpolation in C# 6.0

Content

As we all know Microsoft has launched a new version of C# called C# 6.0 with Visual Studio Ultimate 2015 Preview and there is a new feature in C# 6.0 that is based on "String interpolation".

This feature allows us to eliminate the use of "string.Format()" or formatted syntax where we can replace each format item in a specified string with the text equivalent of a corresponding object's value like:

  1. string.Format("{0} {1}",arg0, arg1);   
or
  1. Console.WriteLine("{0} {1}",arg0, arg1);  
Let's first see the old feature.

I am using Visual Studio Ultimate 2015 Preview.

Visual Studio Ultimate 2015 Previe

Open Visual Studio 2015 and select "File" -> "New" -> "Project" and fill in the project name such as "Console Application1".

console application

After creating the project, I will access some common static methods in "program.cs" without the help of a class name every time.

Now I will write some code that will print the string value in a formatted way.

Code
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         string FirstName = "Rahul";  
  6.         string LastName = "Bansal";  
  7.           
  8.         string PrintString = string.Format("My First Name is {0}   
  9. Last Name is {1}",FirstName, LastName);  
  10.   
  11.         Console.WriteLine(PrintString);  
  12.   
  13.         Console.ReadKey();  
  14.   
  15.     }  
  16. }  
Note: Here I am creating a formatted string using "string.Format()" that will replace each format item in the specified string on the basis of object sequence.

string Format

Output:

Output

But in C# 6.0, we can get the same result without using "string.Format()" more easily where we can put the object in the string directly.

Syntax: "\{arg0}"
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         string FirstName = "Rahul";  
  6.         string LastName = "Bansal";  
  7.   
  8.         string PrintString = "My First Name is \{FirstName} and Last Name is \{LastName}";                  
  9.   
  10.         Console.WriteLine(PrintString);  
  11.   
  12.         Console.ReadKey();  
  13.   
  14.     }  
  15. }  
cs code

That will provide the same result.

Output

result

Conclusion

Now you understand the new feature of C# 6.0 that allows the use of "String interpolation" in an easy way.