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
  • 23,396
  • 63
  • 179
  • 330

2 Answers2

5

Braces need to be escaped:

string test = string.Format("{{img: \"{0}\", html: \"{1}\"}}", "images/a.png", "<div></div>");
usr
  • 165,323
  • 34
  • 234
  • 359
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
  • 269,602
  • 39
  • 394
  • 697