Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WriteLine string containing '{' character throws FormatException in C# [duplicate]

Tags:

c#

.net-2.0

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?

like image 469
Mr. Boy Avatar asked Feb 18 '23 13:02

Mr. Boy


1 Answers

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, "}");
like image 165
Spontifixus Avatar answered Apr 29 '23 11:04

Spontifixus