Easily format strings – String interpolation in C# 6.0

By | November 26, 2014

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.


3 thoughts on “Easily format strings – String interpolation in C# 6.0

  1. Pingback: Download PPT – “A lap around C# 6.0 and Visual Studio 2015 Preview” – MUGH Dev Day– 29th Nov 2014 | Abhijit's World of .NET

  2. Pingback: 10 New features of C# 6.0 that you should know | Abhijit's World of .NET

  3. Fab

    Is it compatible with the use of refactoring functionnality in VS ?

Comments are closed.