Coder Perfect

In an interpolated string, how do you utilize the ternary operator?

Problem

I’m not sure why this code isn’t compiling:

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

It works perfectly if I divide it into two parts:

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

Asked by Nate Barbettini

Solution #1

According to the paperwork:

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

Console.WriteLine($"The current hour is {hours:hh}")

Wrapping the conditional in parenthesis is the solution:

var result = $"Descending {(isDescending ? "yes" : "no")}";

Answered by Nate Barbettini

Post is based on https://stackoverflow.com/questions/31844058/how-to-use-the-ternary-operator-inside-an-interpolated-string