Search code examples
c#string-interpolationc#-11.0

Write other C# code in an interpolated string?


In C# 11 we can now include newlines in an interpolated string. So we can write code like this:

    string pageTitle = "";
    string header = $"Header: {
      pageTitle switch
      {
        "" => "No title",
        _ => pageTitle
      }}";

Is there a way to write other code here beyond the switch statement?

I tried an if and it tells me that if is an invalid expression term.

    string header51 = $"Header: {
      if (pageTitle5 == "")
      {
        "No title";
      }
      else
      {
        pageTitle5;
      }  
    }";

Are there other statements beyond switch that work here?


Solution

  • Every expression will work. In C#, if is not an expression, but a statement.

    However, the ternary operator yields an expression:

    string header51 = $"Header: {
      (pageTitle5 == "" 
          ? "No title"
          : pageTitle5)
      }";
    

    switch works in your example, because you do not use the switch statement but a switch expression.