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}";
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.
You can do that directly with string interpolation, simply by using the ternary operator inside the string: Download, Edit & Run this example!
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"? .
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.
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")}";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With