3

I have an interpolated string which ends with an argument followed by a closing brace. It needs to have a formatting argument, however the string is taking the first double brace as the escaped brace and remaining as the brace closing the argument:

> $"foo:{16:x}"
"foo:10"
> $"foo:{16:x}}}"
"foo:x}"

How to I correctly write the interpolated string so that I get foo:10}?

BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • 2
    Impressively, there's even a special error message if you try to escape the `}` as `\u007d`! Someone was really fond of their grammar. – Jeroen Mostert Apr 17 '18 at 10:21
  • [Related](https://stackoverflow.com/q/42142003/1997232). – Sinatr Apr 17 '18 at 10:27
  • [Also related.](https://stackoverflow.com/questions/40016188/how-to-use-string-format-to-format-a-hex-number-surrounded-by-curly-brackets) – Matthew Watson Apr 17 '18 at 10:35
  • You're right @JeroenMostert. `Error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.`. That just seems mean. – BanksySan Apr 17 '18 at 10:56

1 Answers1

7

There's no direct syntax for that, unfortunately;

$"foo:{16:x}{'}'}" // or $"foo:{16:x}{"}"}"

is a hack that'll work; otherwise, perhaps simply concatenate

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Personally, as far as hacks go, I'd prefer to leave the `}` out of it: `$"foo:{16:x}{null}}}"` or `$"foo:{16:x}{""}}}"` also work. But that's perhaps just a matter of opinion. –  Apr 17 '18 at 10:27
  • 2
    @hvd yeah, once you're down to choosing your *favorite* ugly hack, it is a poor choice – Marc Gravell Apr 17 '18 at 10:30
  • That's what I was thinking. Interestingly, concatenation doesn't work as the result isn't a `FormattableString`. – BanksySan Apr 17 '18 at 10:48
  • @BanksySan you never specified that it *had to be* a `FormattableString` :) the compiler actively prefers *not* to do that - see `Foo($"test {val}");` with `Foo(string x)` and `Foo(FormattableString x)` to see what I mean – Marc Gravell Apr 17 '18 at 10:49
  • It doesn't have to be (my use case is that it is) but the problem exists whether it is there or not. – BanksySan Apr 17 '18 at 10:53
  • @EhsanSajjad do you mean the comment above? if so: "it chooses `Foo(string)`, not `Foo(FormattableString)`" - that do? – Marc Gravell Apr 17 '18 at 12:00