C# interpolated string with conditional-operator

C#Conditional OperatorString Interpolation

C# Problem Overview


I tried to use the conditional operator inside an interpolated string, but because it has a colon in it, the compiler thinks that after the colon comes a format string.

$"test {foo ? "foo is true" : "foo is false"}";

How can I use this type of statement? The only thing that comes to my mind is something like this:

var fooString = foo ? "foo is true" : "foo is false";
$"test {fooString}";

C# Solutions


Solution 1 - C#

You need to put the string in parentheses within {}, so: {(1 == 1 ? "yes" : "no")}.

Solution 2 - C#

$"test {(foo ? "foo is true" : "foo is false")}";   

The code inside the parentheses returns a variable, and that's the only thing allowed inside the curly brackets. The colon ':' is a special character in string interpolation, hence it needs to be parenthesised.

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
QuestionwertzuiView Question on Stackoverflow
Solution 1 - C#Tomáš HübelbauerView Answer on Stackoverflow
Solution 2 - C#GregoryHouseMDView Answer on Stackoverflow