.net 2.0 - WriteLine string containing '{' character throws FormatException in C# -
this question has reply here:
how escape braces (curly brackets) in format string in .net 4 answers
this throws formatexception:
console.writeline("strict digraph {0}\n{", project.projectname);
but fine:
console.writeline("strict digraph {0}\n", project.projectname);
i need trailing '{' , \{
isn't valid escape code. wrong code , how create work?
you need escape curly bracket curly bracket:
console.writeline("strict digraph {0}\n{{", project.projectname);
for farther info have @ relevant msdn article composite formatting , section "escaping braces".
is states that
opening , closing braces interpreted starting , ending format item. consequently, must utilize escape sequence display literal opening brace or closing brace. specify 2 opening braces ("{{") in fixed text display 1 opening brace ("{"), or 2 closing braces ("}}") display 1 closing brace ("}"). braces in format item interpreted sequentially in order encountered. interpreting nested braces not supported.
but mind you. can result in unexpected behavior: take format string {{{0:d}}}
example. should output "{10}" example, shouldn't it?. should, doesn't. msdn-article linke above states that
the first 2 opening braces ("{{") escaped , yield 1 opening brace. the next 3 characters ("{0:") interpreted start of format item. the next character ("d") interpreted decimal standard numeric format specifier, next 2 escaped braces ("}}") yield single brace. because resulting string ("d}") not standard numeric format specifier, resulting string interpreted custom format string means display literal string "d}". the lastly brace ("}") interpreted end of format item. the final result displayed literal string, "{d}". numeric value formatted not displayed.
to circumvent msdn suggests utilize next code:
var result = string.format("{0}{1:d}{2}", "{", 10, "}");
c# .net-2.0