How to use the ternary operator inside an interpolated string?

C#.NetTernary OperatorString InterpolationC# 6.0

C# Problem Overview


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

C# Solutions


Solution 1 - C#

According to the documentation: > The structure of an interpolated string is as follows: > > { <interpolationExpression>[,<alignment>][:<formatString>] }

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

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

The solution is to wrap the conditional in parenthesis:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNate BarbettiniView Question on Stackoverflow
Solution 1 - C#Nate BarbettiniView Answer on Stackoverflow