I'll preface this question with, I already have the answer. But I suspect other people ran into similar scenarios and I wanted to share my solution.
Question: How can I use a switch expression in Balzor to render components?
I have a scenario where I have an object with a string property and I want to render different buttons based on the string value. Using a switch statement it looks something like this
@switch(myObject.SomeStringValue)
{
    case "StringValueOne": <ButtonComponent OnClick="@DoAThing"/> break;
    case "StringValueTwo": <ButtonComponent OnClick="@DoTwoThing"/> break;
    case "StringValueThree": <ButtonComponent OnClick="@DoThreeThing"/> break;
    default: <ButtonComponent OnClick="@DoSomethingElse"/> break;
}
My problem is I wanted to match multiple string values in each case, using pattern matching...
 case is "StringValueOne" or "AnotherMatchingValue": <ButtonComponent OnClick="@DoAThing"/> break;
Based on the C# docs, I couldn't find a way to use a switch statement and pattern matching together.
Now, in general I like the syntax of switch expressions better than switch statements. I wanted to be able to use a switch expression in Blazor to get a similar outcome to the above switch statement which works natively in a razor file. How could I use a switch expression to accomplish the same goal?
Well, here's an answer folks!
@(myObject.SomeStringValue switch
{
    "StringValueOne" or "AnotherMatch" => (@<ButtonComponent OnClick="@DoAThing"/>),
    "StringValueTwo" or "MatchTwo" => (@<ButtonComponent OnClick="@DoTwoThing"/>),
    "StringValueThree" or "MatchThree" => (@<ButtonComponent OnClick="@DoThreeThing"/>),
    _ => (@<ButtonComponent OnClick="@DoSomethingElse"/>)
})
Let me know if you find another way to do this or if this doesn't work for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With