How to use the ternary operator inside an interpolated string?

Nate Barbettini Source

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}";


answered 3 years ago Nate Barbettini #1

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")}";

comments powered by Disqus