79

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}";
Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125
wertzui
  • 5,148
  • 3
  • 31
  • 51
  • 2
    That's an [Interpolated string](https://msdn.microsoft.com/en-GB/library/dn961160.aspx). [Verbatim strings](https://msdn.microsoft.com/en-GB/library/362314fe.aspx) are those that start with `@"` and may contain characters that would normally need escaping. – Damien_The_Unbeliever Nov 02 '15 at 08:58

2 Answers2

197

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

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125
38
$"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.

bornfromanegg
  • 2,826
  • 5
  • 24
  • 40
GregoryHouseMD
  • 2,168
  • 1
  • 21
  • 37