Write other C# code in an interpolated string?
Asked Answered
V

2

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?

Vladi answered 6/4, 2023 at 20:45 Comment(4)
it needs expression not statment. do pageTitle==""?"No title":PageTitleBrooder
Side note: code in the question does not have "the switch statement"...(medium.com/@time4ish/…)Mcdaniels
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)}"Aa
Ah! Thank you @AlexeiLevenkov. I was wondering why the syntax didn't match the docs for "switch statement". Thanks for the link.Vladi
C
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.

Conventioneer answered 6/4, 2023 at 20:48 Comment(2)
And anything goes if wrapped as IIFEMcdaniels
For anyone else reading this ... the above code doesn't work as is. The ternary operator expression needs to be within parens ( ) to compile.Vladi
N
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

Nodab answered 7/4, 2023 at 2:31 Comment(1)
Nice! So I can pass an anonymous function (or call a named function). Thanks!Vladi

© 2022 - 2024 — McMap. All rights reserved.