roslyn: Strange syntax error in interpolated string when using ?:
$"{1 / Environment.TickCount == 0 ? 1 : 2}"
Here, the "1 " part has a red squiggly saying “: expected”. I don’t know whether this code is supposed to compile or not but the message does not make sense to me. I would not “expect” a “:” character right after the question mark under any circumstances.
The workaround $"{(1 / Environment.TickCount == 0 ? 1 : 2)}"
works fine.
I guess this is a low priority issue but I still wanted to report it so that it can be triaged and tracked.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 20 (12 by maintainers)
Links to this issue
Commits related to this issue
- Improve the syntax error when a conditional expression used in an interpolated string Fixes #12214 — committed to gafter/roslyn by gafter 7 years ago
- Improve the syntax error when a conditional expression used in an interpolated string (#23265) Fixes #12214 — committed to dotnet/roslyn by gafter 7 years ago
I insist that using “?:” operator inside an interpolated string handled WRONG WAY. We waited year while you discussing proper syntax for interpolation, and now, when you introduced these clumsy {} (instead of one symbol $ ), you say “it’s not a bug”. IT IS a bug. Once you limit substitution expression with braces {}, take full responsibility to handle it properly. And nobody care on what you base your formatting - we didn’t ask you to use “string.Format” - we asked just simple substitution, like “Hello, $UserName!”.
The error will be
error CS8361: A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation. Parenthesize the conditional expression.
@gafter: I offered same solution like Nemerle has: dollar sign + verbatim mode. Better if these strings will have different quotes. Say, backtick (like in D). Finally it will look like this:
var s = ~bacltick here~ Today is $day Temp is $temp Last line of string~bacltick here~;
It’s simple, CLEAR, obvious solution, usable for 99% cases. Where not, use old, good strings, Format(), etc. Yes, it’s not “hyper universal solution”, but I’m tired of “universal architectors”, who convert every task into idiotically complex solution (his code) and same idiotically complex usage (my code). Overengineering in other words.
Any expression, unary or sixnary, have to be completely parsed in interpolation string as a whole expression, NOT to intersecting with any “formatting” characters. It’s just stupid - introduce feature to SIMPLIFY our life and make it so abstract/clumsy that it become UNUSABLE. What organ you use to think, team?? Just keep in your student head: $“… {a ? b : c}…” MUST WORK. Period. No excuses, no annoying explanations why you didn’t make it properly.