Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C# 8 new switch replace a code block containing multiple ? : ? : expressions?

Here's an example of what I am doing now:

return
    shpc == 0 ? "Currently, based on your selection below, you have not yet identified any hidden cards in your card deck." :
    shpc == 1 ? "Currently, based on your selection below, you have one hidden card in your card deck." :
                $"Currently, based on your selection below, you have {shpc} hidden cards in your card deck. These will not be visible.";

The code words but not having much knowledge of what was added to switch I wonder if this could also be done with a switch expression?

like image 821
Samantha J T Star Avatar asked Nov 16 '25 08:11

Samantha J T Star


2 Answers

Try this

return shpc switch 
{
    0 => "Currently, based on your selection below, you have not yet identified any hidden cards in your card deck.",
    1 => "Currently, based on your selection below, you have one hidden card in your card deck.",
    _ => $"Currently, based on your selection below, you have {shpc} hidden cards in your card deck. These will not be visible."
};
like image 159
Roman Marusyk Avatar answered Nov 18 '25 22:11

Roman Marusyk


Definitely:

return shpc switch 
{
    0 => "Currently, based on your selection below, you have not yet identified any hidden cards in your card deck.",
    1 => "Currently, based on your selection below, you have one hidden card in your card deck.",
    _ => $"Currently, based on your selection below, you have {shpc} hidden cards in your card deck. These will not be visible."
};


like image 32
Alvin Sartor Avatar answered Nov 18 '25 21:11

Alvin Sartor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!