4

This throws a FormatException:

Console.WriteLine("strict digraph {0}\n{", project.ProjectName);

But this is fine:

Console.WriteLine("strict digraph {0}\n", project.ProjectName);

I need the trailing '{' and \{ isn't a valid escape code. What exactly is wrong with my code and how do I make it work?

2
  • Console.WriteLine("strict digraph {0}\n{{", project.ProjectName); Commented Feb 11, 2013 at 17:08
  • In addition to the below answers, here's the MSDN article on "Composite Formatting" (the relevant section is a ways down, "Escaping Braces") msdn.microsoft.com/en-us/library/txafckwd.aspx Commented Feb 11, 2013 at 17:10

1 Answer 1

7

You will need to escape a curly bracket by another curly bracket:

Console.WriteLine("strict digraph {0}\n{{", project.ProjectName);

For further information have a look at the relevant MSDN article Composite Formatting and its section "Escaping Braces".

Is states that

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 ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.

But mind you. this can result in unexpected behavior: Take the format string {{{0:D}}} for example. It should output "{10}" for example, shouldn't it?. It should, but it doesn't. The MSDN-article linke above states that

  1. The first two opening braces ("{{") are escaped and yield one opening brace.
  2. The next three characters ("{0:") are interpreted as the start of a format item.
  3. The next character ("D") would be interpreted as the Decimal standard numeric format specifier, but the next two escaped braces ("}}") yield a single brace. Because the resulting string ("D}") is not a standard numeric format specifier, the resulting string is interpreted as a custom format string that means display the literal string "D}".
  4. The last brace ("}") is interpreted as the end of the format item.
  5. The final result that is displayed is the literal string, "{D}". The numeric value that was to be formatted is not displayed.

To circumvent that MSDN suggests that to use the following code:

var result = string.Format("{0}{1:D}{2}", "{", 10, "}");
Sign up to request clarification or add additional context in comments.

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.