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?

0

3 Answers 3

16

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

String.Format("Foo {{ Bar={0} }}", this.Bar);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.