huoxudong125
huoxudong125

Reputation: 2056

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 **

Upvotes: 5

Views: 4791

Answers (1)

HABJAN
HABJAN

Reputation: 9338

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)

Upvotes: 12

Related Questions