Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine string interpolation and string.format

Tags:

c#

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}";
like image 360
Tom Avatar asked Sep 26 '16 11:09

Tom


People also ask

What is the difference between string interpolation and string concatenation?

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.

What is the correct syntax for string interpolation?

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.

Can we use expressions Inside string interpolation?

String interpolation is a technique that enables you to insert expression values into literal strings.

Is string format faster than concatenation C#?

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.


1 Answers

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.

like image 127
adam0101 Avatar answered Sep 21 '22 20:09

adam0101