Search code examples
f#string-interpolation

Ternary conditional operator in interpolated strings in F#


Is it possible to use the ternary conditional operator in an interpolated string?
Something like:

printfn $"""This is a string{($", and here's the inner string: {innerString}!" if boolFlag  else "!")}\n"""

Solution

  • You can use any valid F# expression when using string interpolation, including the if expression. Just use the standard F# way of writing it if <boo> then <e1> else <e2>:

    let boolFlag = true
    let innerString = "Yo"
    
    printfn $"""This is a string{
      if boolFlag then $", and here's the inner string: {innerString}!" 
      else "!"}\n"""