0

String.format throws incorrect format exception when there is an extra } in the string as shown in the snippet below

 var input = "1";
 var data = string.Format(@"{0}}", input);

I was able to resolve the issue by adding an extra } as shown below

var data = string.Format(@"{0}}}", input);

However I need to know if there is any better solution to this issue

Maverick
  • 1,396
  • 5
  • 22
  • 42
Shaiju Janardhanan
  • 546
  • 1
  • 11
  • 21

2 Answers2

3

I would highly recommend using C# 6 String Interpolation feature as it is more readable and maintainable:

var data = $"{{{input}}}";

When the string grows large, you'll see the benefit of Visual Studio formatting and coloring your string like this:

enter image description here

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • that looks a lot cleaner. Thanks. But one small doubt, does the substitution of parameters result in creation of a new string everytime a substitution is made? – Shaiju Janardhanan Aug 08 '16 at 06:18
  • @ShaijuJanardhanan The compiler transforms the above into `String.Format` behind the scenes. So this is just a syntactic sugar, nothing different from your approach expect that it is cleaner and more readable and maintainable. – Zein Makki Aug 08 '16 at 06:21
1

No, this is the intended functionality. From the docs:

How do I include literal braces ("{" and "}") in the result string? A single opening or closing brace is always interpreted as the beginning or end of a format item. To be interpreted literally, it must be escaped. You escape a brace by adding another brace ("{{" and "}}" instead of "{" and "}"), as in the following method call:

result = String.Format("The text has {0} '{{' characters and {1} '}}' characters.", 
             nOpen, nClose);
Blue
  • 22,608
  • 7
  • 62
  • 92