String Formating in c# 6

format strings

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
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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s