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:
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()
.
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.
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.
CodeProject