Fairway Technologies Blog


String Interpolation in C# 6.0

In Development No Comments

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:

<pre>string first = "Paul";<br>string last = "Sheriff";<br>Console.WriteLine(string.Format("{0} {1}", first, last));</pre>

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

<pre>string first = "Paul";<br>string last = "Sheriff";<br>Console.WriteLine($"{first} {last}");</pre>

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.

<pre>string dir = "Windows";<br>Console.WriteLine($@"C:\{dir}");</pre>

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

Have fun with this new feature of C# 6.0.

Plan Your Technology Team with This Online Assessment Tool

Subscribe to Email Updates

Build a Technology Dream Team. Start with This Online Assessment. →