Monday, July 20, 2015

String Interpolation

String Interpolation is an interesting method of being able to access properties directly within a string. Once upon a time in order to include properties into a string you would have to do something like this :

int age = 16;
string mystr = "My age is" + age.ToString();

Essentially a string concatenation and then returning other types as a string.

Then we had string.Format which I thought it was fantastic with the autoconversion of types to string - so we had something like this:

string.Format("My age is {0}", age);


Now, this was very handy and made string concatenation simple and easy to read (have you ever encountered someone else's string concatenation and wondered wtf)?


One of the downfalls of string.Format was that you had to remember the order to add the variable. Since string.Format uses a format as {0}, {1}, {2}, etc... means that your arguements will need to be in the exact order. If you have alter your code delete a string block in the middle then you have to re-sequence everything.

String Interpolation aims solve some of these issues by allowing you to use name properties in your string. The code will look something like this :

int age = 16;
string mystr = $"My age {age}";

Notice, the "$" in front of the string, and also note that the property is surrounded by parenthesis.

0 comments:

Post a Comment