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
  • 27,091
  • 26
  • 115
  • 147

3 Answers3

16

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

String.Format("Foo {{ Bar={0} }}", this.Bar);
Dustin Kingen
  • 19,915
  • 7
  • 49
  • 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
  • 208,592
  • 21
  • 221
  • 278
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