HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How to use the ternary operator inside an interpolated string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howusetheinterpolatedternaryoperatorstringinside

Problem

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

Solution

According to the documentation:

The structure of an interpolated string is as follows:

{ [,][:] }

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

Code Snippets

Console.WriteLine($"The current hour is {hours:hh}")
var result = $"Descending {(isDescending ? "yes" : "no")}";

Context

Stack Overflow Q#31844058, score: 1145

Revisions (0)

No revisions yet.