Conditional to Switch/Switch to Conditional

Purpose

Converts nested if-else blocks into a single switch (Select) statement or vice versa. It is recommended to use the switch statement when the selector is discrete. On the other hand, if you need to check continuous ranges, you should use the if-else cascade. The manual conversion between these two approaches requires a lot of formatting work, which can be done automatically by this Refactoring.

Availability

  • The Conditional to Switch Refactoring is available when the caret is on an if statement that has a corresponding else block.
  • The Switch to Conditional Refactoring is available when the caret is on a switch (Select) statement.

Usage

  1. 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.

    if (i == 1)
        i++;
    else {
        if (i == 2)
            i--;
        else
            i = 0;
    }
    
  2. Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu.
  3. Select Conditional to Switch from the menu (Switch to Conditional if you are converting the switch (Select) statement into a nested conditionals).

After execution, the Refactoring converts the nested sequence of conditionals into a single switch (Select) statement or vice versa.

switch (i) {
    case 1:
        i++;
        break;
    case 2:
        i--;
        break;
    default:
        i = 0;
        break;
}

See Also