Conditional to Switch/Switch to Conditional
- 2 minutes to read
Purpose
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.
Availability
- The Conditional to Switch refactoring is available when the caret is in an if statement that has a corresponding else block.
- The Switch to Conditional refactoring is available when the caret is in a switch (Select) statement.
Usage
Place the caret on the if statement that has a corresponding else block.
NOTE
The blinking cursor shows the caret's position at which the Refactoring is available.
- Use 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;
}
See Also