I'm just wondering if there is a possibility to combine string interpolation, which was introduced in C# 6.0 and string.format? Any smarter ideas like this?
string fancyString = $"My FancyString was created at { DateTime.Now }" + " and I want to add some static with string.format like {0}";
You can think of string concatenation as gluing strings together. And, you can think of string interpolation without strings as injecting strings inside of other strings.
Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.
String interpolation is a technique that enables you to insert expression values into literal strings.
Format (using Reflector) and it actually creates a StringBuilder then calls AppendFormat on it. So it is quicker than concat for multiple stirngs. Quickest (I believe) would be creating a StringBuilder and doing the calls to Append manually. Of course the number of "many" is up for guessing.
Escape your {0}
by writing it as {{0}}
so string interpolation leaves it alone. Then you can pass the string into string.Format
to replace the {0}
.
For those wondering why you'd want to do this, I can imagine one possibility where you want to do some sort of reusable template such as:
var urlTemplate = $"<a href='{BaseHref}/some/path/{{0}}'>{{1}}</a>";
var homeLink = string.Format(urlTemplate, "home.html", "Home");
var aboutLink = string.Format(urlTemplate, "about.html", "About Us");
Of course this example is too simple to warrant such a technique, but imagine if you had a template with a very large number of variables and you only cared to change a couple from one rendered template to the next. This would be much more readable than having {32}, {33}, {34}...
etc. in your template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With