4

How can I format a String in C# where the pattern has brackets? When I run the following statement...

String.Format("Foo { Bar={0} }", this.Bar);

... I receive a runtime exception:

System.FormatException: Input string was not in a correct format.

Should I have to escape the brackets? How to?

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148

3 Answers3

16

Escape the brackets by doubling the brackets like {{ and }}

String.Format("Foo {{ Bar={0} }}", this.Bar);
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
4

This situation is explained on MSDN in the article Composite Formatting - Escaping Braces

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}").

So this should be your solution

String.Format("Foo {{ Bar={0} }}", this.Bar);
Steve
  • 213,761
  • 22
  • 232
  • 286
4

Try using double curly braces, so it looks like:

String.Format("Foo {{ Bar={0} }}", this.Bar);

Looks like it has already been answered: Escape curly brace '{' in String.Format

Community
  • 1
  • 1
uv_man
  • 224
  • 1
  • 3