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?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • `Console.WriteLine("strict digraph {0}\n{{", project.ProjectName);` – Jodrell Feb 11 '13 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") http://msdn.microsoft.com/en-us/library/txafckwd.aspx – Chris Sinclair Feb 11 '13 at 17:10

1 Answers1

8

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, "}");
Spontifixus
  • 6,570
  • 9
  • 45
  • 63