coderushforroslyn-115432-refactoring-assistance-conditional-to-switch-switch-to-conditional.md
Converts nested if-else blocks into a single switch ( Select ) statement or vice versa. We recommend using the switch statement when the selector is discrete. If you need to check continuous ranges, use the if-else cascade.
Conditional to Switch and Switch to Conditional refactorings also support pattern matching.
Place the caret on the if statement that has a corresponding else block.
Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
Select Conditional to Switch from the menu ( Switch to Conditional if you are converting the switch ( Select ) statement into nested conditionals).
After execution, the Refactoring converts the conditionals into a single switch ( Select ) statement or vice versa.
public static int GetTotal(IEnumerable<object> values) {
var sum = 0;
foreach (var item in values) {
switch (item) {
case int val:
sum += val;
break;
case IEnumerable<object> sublist:
sum += GetTotal(sublist);
break;
}
}
return sum;
}
Select Case i
Case 1
i += 1
Case 2
i -= 1
Case Else
i = 0
End Select
See Also