Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the ternary operator inside an interpolated string?

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}"; 
like image 335
Nate Barbettini Avatar asked Aug 05 '15 22:08

Nate Barbettini


People also ask

Can we use expressions Inside string interpolation?

String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.

Which of the following operator is used for string interpolation method?

You can do that directly with string interpolation, simply by using the ternary operator inside the string: Download, Edit & Run this example!

Can we use string in ternary operator?

The + operator causes concatenation with strings and forces all primitive variables to attempt to represent themselves as strings as well. false evaluates as the string "false" creating the statement "test: false" . The parser is now ready to evaluate the first part of the ternary: "test: false"? .

How do you handle 3 conditions in a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


1 Answers

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")}"; 
like image 54
Nate Barbettini Avatar answered Sep 23 '22 00:09

Nate Barbettini