Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why escape brackets (curly braces) in a format string in .NET is '{{' or '}}" not '\{' or '\}'

There is a question how-to-escape-brackets-curly-braces-in-a-format-string-in-net but There none to describe the reason? why is using {{ or }} not \{ or \}.

eg. string s = String.Format("{{ hello to all }}"); why not using \{ like string escape in string such as: \b\n\t

**I want to know the deepin reason or from the language design **

like image 543
huoxudong125 Avatar asked Jun 09 '14 04:06

huoxudong125


1 Answers

Format strings are interpreted during the runtime (not during compile time)

If C# would allow to enter \{ or \} it would be stored in the string as { and } respectively. The string.Format function then reads this string to decide if a formatting instruction is to be interpreted, e.g. {0}. Since the \{ resulted in { character in the string, the String.Format function could not decide that this is to be taken as a format instruction or as literal {. So, string.Format treats {{ as literal {. Analogous }} for }.

Escaping in C#:

- character literal escaping:   e.g. '\'', '\n', '\u20AC' (the Euro € currency sign), '\x9' (equivalent to \t))
- literal string escaping:  e.g. "...\t...\u0040...\U000000041...\x9..."
- verbatim string escaping: e.g. @"...""..."
- string.Format escaping:   e.g. "...{{...}}..."
- keyword escaping: e.g. @if (for if as identifier)
- identifier escaping:  e.g. i\u0064 (for id)
like image 199
HABJAN Avatar answered Sep 22 '22 18:09

HABJAN