Reputation: 17
I’m using if/else statements to check which radio button is clicked. How to use a switch statement instead of if/else.
else if (CBLeather.Checked && CBComputerNav.Checked && !CBStereo.Checked) {
accessories = Accessories.LeatherAndNavigation;
} else if (CBComputerNav.Checked && CBLeather.Checked && CBStereo.Checked) {
accessories = Accessories.All;
} else {
accessories = Accessories.None;
}
Upvotes: 0
Views: 75
Reputation: 1933
Although your use case is not meant for a switch statement but there is a crazy way of doing so :)
switch (0)
{
case 0 when (CBLeather.Checked && CBComputerNav.Checked && !CBStereo.Checked):
accessories = Accessories.LeatherAndNavigation;
break;
case 0 when (CBComputerNav.Checked && CBLeather.Checked && CBStereo.Checked):
accessories = Accessories.All;
break;
default:
accessories = Accessories.None;
break;
}
Again, it works but not advisable!
Upvotes: 0
Reputation: 62498
You cannot put switch case here i think as you have multiple condition for code branching.
You can extract methods from these conditions and just call them in your if blocks something like:
private bool IsLeatherAndNavigation()
{
return CBLeather.Checked && CBComputerNav.Checked && !CBStereo.Checked;
}
and use :
if (IsLeatherAndNavigation())
{
accessories = Accessories.LeatherAndNavigation;
}
and can be reused wherever required instead of putting the duplicated if conditions everywhere around in the class.
Upvotes: 2