top of page

Let's talk Interpolated Strings

Buzzzzzzzzzword ….interpolated. What in the holy hell is that? Welllll, this is a sweet way that was added starting with C# 6.0 to build a string just a tad easier than using a Stringbuilder.


Normally, when we need to slap together a structured email about something erroring, we do something like this:

 
var StringB = new StringBuilder();
StringB.AppendLine ("<table border='0' cellspacing='10' cellpadding='1' width='300'>");
StringB.AppendLine ("<tr>");
StringB.AppendLine ("The Error: “);
StringB.AppendLine (ex.Message);
BodyBuilder.AppendLine();
StringB.AppendLine ("Psst ….. this error is garbage. Love, Microsoft");
StringB.AppendLine ("</tr>");
StringB.AppendLine ("</table>");
BodyBuilder.AppendLine(). AppendLine ();
Mail.SendeMail (EmailTo, EmailFrom, "Craptastic Error Happened", "Error was: " + StringB);
 

Now, interpolated string allow a way faster way to combine variables into your string. You tap into the Format method and Visual Studio just “knows” that your variables are in order. Like so:

 
var StringB = String.Empty;
StringB = string.Format("<table border='0' cellspacing='10' cellpadding='1' width='300'><tr> The Error: {0} </br> Psst ….. this error is garbage. Love, Microsoft</tr></table></br>”, ex.Message);
 
Mail.SendeMail (EmailTo, EmailFrom, "Craptastic Error Happened", "Error was: " + StringB );
 

The two examples above will give you the exact same result, but the second one offers you a shortened way to write it. Wait, what? “How did that work again, Liv?” I got you, no worries.


So the first part is the string we want to create. We want the static portion listed first. Then, any variables are added after the static string.


String.Format(string you want to add dynamic variable to, value 0, value 1, value 2, value 3, etc);


OR


String.Format(“replace {0} and {1} plus {2}”, this, that, those);


Results in “replace this and that plus those”

Keep in mind this is a 0 based value, so always begin with {0} rather than any other number.

For the most part, interpolated strings have become my standard, rather than the StringBuilder class. I haven’t found any situation where interpolation doesn’t do what’s needed, but I’m sure there are reasons not to use interpolation.

Surprisingly, Microsoft has a great explanation on how these guys work, so for more detail go to the Microsoft MSDN Link and scroll down to Figure 6.



Questions? Comments? Down here:

49 views0 comments

Commentaires


bottom of page