5

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?

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • 1
    it needs expression not statment. do `pageTitle==""?"No title":PageTitle` – pm100 Apr 06 '23 at 20:48
  • 2
    Side note: code in the question does not have "the switch statement"...(https://medium.com/@time4ish/csharp-switch-statement-vs-switch-expression-explained-b0046058eee6) – Alexei Levenkov Apr 06 '23 at 20:53
  • The code blocks of interpolated strings must be expressions, they must evaluate to something, or "return" something, which is why the switch expression works because it returns something. Also tangential nitpick: use `string.IsNullOrEmpty()` which can then be used in a very clean ternary expression -> `string header = $"Header: {(string.IsNullOrEmpty(pageTitle5) ? "No Title" : pageTitle5)}"` – Narish Apr 06 '23 at 20:59
  • Ah! Thank you @AlexeiLevenkov. I was wondering why the syntax didn't match the docs for "switch statement". Thanks for the link. – DeborahK Apr 06 '23 at 21:13

2 Answers2

6

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.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • 1
    And anything goes if wrapped as [IIFE](https://stackoverflow.com/questions/18279520/are-there-any-official-ways-to-write-an-immediately-invoked-function-expression) – Alexei Levenkov Apr 06 '23 at 20:55
  • 1
    For anyone else reading this ... the above code doesn't work as is. The ternary operator expression needs to be within parens ( ) to compile. – DeborahK Apr 06 '23 at 21:19
  • 1
    @DeborahK: Thanks, should be fixed now. – Heinzi Apr 06 '23 at 21:58
1

If you prefer using if else statement, you can write the code like this :

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

This way you have more flexibility to do extra logics in the if else block

Fitri Halim
  • 584
  • 4
  • 11