Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#6.0

String Interpolation in C# 6.0

3.86/5 (5 votes)
14 Jan 2017CPOL 8.9K  
String interpolation in C# 6.0

I just found this handy shorthand for string.Format() which is available in C# 6.0. I am sure you have all used string.Format() before. Let's say you want to do a little formatting with some data in some variables like the following:

C#
string first = "Paul";
string last = "Sheriff";
Console.WriteLine(string.Format("{0} {1}", first, last));

In C# 6.0, you may now use the string interpolation character, the dollar sign, instead of the string.Format().

C#
string first = "Paul";
string last = "Sheriff";
Console.WriteLine($"{first} {last}");

Both of the above pieces of code will place the string "Paul Sheriff" into your output window.

I really like this new format. It is much easier to read and understand where exactly your variables are going without having to count the number of parameters and figure out which ones go where in your string.

You may also combine the $ with the @ sign if you are going to have a backslash in your string. You must specify them in the order $@ for the interpolation to work correctly. Here is an example of using these two together.

C#
string dir = "Windows";
Console.WriteLine($@"C:\{dir}");

The above code will display the string "C:\Windows" in your output window.

Have fun with this new feature of C# 6.0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)