Skip to main content

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

  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.

    public static int GetTotal(IEnumerable<object> values) {
        var sum = 0;
    
        foreach (var item in values) {
            if (item is int val)
                sum += val;
            else if (item is IEnumerable<object> sublist)
                sum += GetTotal(sublist);              
        }
        return sum;
    }
    
  2. Press 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 nested conditionals).

    conditional-to-switch-menu

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