Search code examples
c#string-interpolation

How do I escape a brace in an interpolated string, after a brace with a format string?


The following crashes:

$"{{{DayOfWeek.Friday:d}}}"

If I put a space after the first closing brace, it works, but I don't want a space there.

So 2 questions:

  1. Why does it crash, instead of treating the last 2 braces as a literal brace?
  2. How can I do what I am trying to do?

Solution

  • Please have a look at Escaping Braces documentation

    For example, consider the format item "{{{0:D}}}", which is intended to display an opening brace, a numeric value formatted as a decimal number, and a closing brace. However, the format item is actually interpreted in the following manner: 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}".

    This is exactly your case, you are getting incorrect format specifier as a result.

    For you code you can try to use the old string.Format

    string.Format("{0}{1:d}{2}", "{", DayOfWeek.Friday, "}");