Click here to Skip to main content
13,247,336 members (90,017 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

6.2K views
1 bookmarked
Posted 14 Jan 2017

String Interpolation in C# 6.0

, 14 Jan 2017
Rate this:
Please Sign up or sign in to vote.
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:

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.

License

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

Share

About the Author

Paul D. Sheriff
Architect Fairway Technologies, Inc.
United States United States
Paul has over thirty years of experience architecting information systems and his expertise is in much demand from Fortune 500 companies. Paul is a top-notch instructor, a pluralsight author, has published 350+ articles, and authored over 14 books on topics ranging from Angular, jQuery, JavaScript, C#, SQL Server and many other .NET technologies. Paul has over 15 courses in the www.pluralsight.com library on topics ranging from Angular, MVC, WPF, XML, jQuery and Bootstrap. Paul speaks at many different conferences and user groups around the world. Contact Paul at psheriff@fairwaytech.com.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 15 Jan 2017
Article Copyright 2017 by Paul D. Sheriff
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid