11

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}";
5
  • 3
    Why would you want to do it ? What can you achieve by doing so that is not possible with string interpolation? Commented Sep 26, 2016 at 11:32
  • And how would you use it exactly? Pass interpolated string to String.Format? Commented Sep 26, 2016 at 11:33
  • you bet you can use stringformat after the interpolation like this string.format(fancyString,SomethingToFillYour{0}With); but why would you ever want to do that? Commented Sep 26, 2016 at 11:35
  • Yes, normally string interpolation should do the whole job, but if you don't want to change your whole code from string.format you search for possibilities to combine both. Commented Sep 26, 2016 at 11:41
  • 2
    Don't think of it in terms of changing code. By all means use interpolation on new stuff, and convert string.Format calls to interpolation during refactoring where appropriate, but changing existing string.Format calls to partial interpolation just sounds like making more of a maintenance mess. Commented Sep 26, 2016 at 11:43

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this answer. It actually helps (helped me) instead of questioning the purpose :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.