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?
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
- The first two opening braces ("{{") are escaped and yield one opening brace.
- The next three characters ("{0:") are interpreted as the start of a format item.
- 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}".
- The last brace ("}") is interpreted as the end of the format item.
- 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, "}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With