How to use the ternary operator inside an interpol

2019-01-03 23:37发布

I'm confused as to why this code won't compile:

var result = $"{fieldName}{isDescending ? " desc" : string.Empty}";

If I split it up, it works fine:

var desc = isDescending ? " desc" : string.Empty;
var result = $"{fieldName}{desc}";

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-04 00:32

According to the documentation:

The structure of an interpolated string is as follows:

$ "{ <interpolation-expression> <optional-comma-field-width> <optional-colon-format> }"

The problem is that the colon is used to denote formatting, like

Console.WriteLine($"Time in hours is {hours:hh}")

So, the tl;dr answer is: wrap the conditional in parenthesis.

var result = $"descending? {(isDescending ? "yes" : "no")}";
查看更多
登录 后发表回答