Easily format strings – String interpolation in C# 6.0

Easily format strings – String interpolation in C# 6.0

Formatting the string values are very common during development. We generally use String.Format() method, that replaces each format item in a specified string with the text equivalent values from the objects. While this is a common, sometimes this is confusing and produce error. Because, we need to specific the place holder for each item and then map them with the objects values. We also need to ensure that we are referring the correct object value for individual place holder. String Interpolation in C# 6.0 makes it much easier and clean.  Using the new String Interpolation, we can directly refer the values rather specifying the place holders.

Here is a small example of using String interpolation.

string Value1 = "Value 1";
string Value2 = "Value 2";

// With String.Format
var stringValue1 = string.Format("{0}- {1}", Value1, Value2);

// With String Interpolation - C# 6.0 early release
// var stringValue2 = "\{Value1}-\{Value2}";

// With String Interpolation 
  var stringValue2 = $"{Value1}-{Value2}";

In the above code snippet both stringValue1  and stringValue2  return the same values, but String Interpolation makes it look more easier and less error prone.  Just think about when you are formatting with multiple properties values with some text just for display, you know where to place which values, rather using some placeholders.

 

DON'T MISS OUT!
Subscribe To Newsletter For your Daily Development Tips and Tricks  

 Best Tips & Tricks on Microsoft Technology Platform 

Invalid email address
We promise not to spam you. You can unsubscribe at any time.
Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

3 Comments to “Easily format strings – String interpolation in C# 6.0”

Comments are closed.