5

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

1 Answer 1

12

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.