2

I am attempting to perform String Interpolation in C#. The input string I am attempting to combine contains many '{}' characters(because its javascript) which seems to be causing an error.

Why cant I perform string interpolation on these strings in C#?

string test = string.Format("{img: \"{0}\", html: \"{1}\"}", "images/a.png", "<div></div>");
// so the output should be
// "{img: \"images/a.png\", html: \"<div></div>\"}"

The error I get is:

Input string was not in a correct format.

Can you tell me how I can acheive my string interpolation?

sazr
  • 24,984
  • 66
  • 194
  • 362

2 Answers2

5

Braces need to be escaped:

string test = string.Format("{{img: \"{0}\", html: \"{1}\"}}", "images/a.png", "<div></div>");
usr
  • 168,620
  • 35
  • 240
  • 369
1

Braces have special meaning to string.Format, so you need to escape them.

See: http://msdn.microsoft.com/en-us/library/txafckwd.aspx

There's no simple way to do what you want, but that documentation page suggests some workarounds.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720