C# interpolated string with conditional-operator

wertzui picture wertzui · Nov 2, 2015 · Viewed 15.9k times · Source

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

Answer

Tomáš Hübelbauer picture Tomáš Hübelbauer · Nov 2, 2015

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