Back to Devexpress

Conditional to Switch/Switch to Conditional

coderushforroslyn-115432-refactoring-assistance-conditional-to-switch-switch-to-conditional.md

latest2.1 KB
Original Source

Conditional to Switch/Switch to Conditional

  • Aug 19, 2021
  • 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.

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

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

csharp
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;
}
vb
Select Case i
    Case 1
        i += 1
    Case 2
        i -= 1
    Case Else
        i = 0
End Select

See Also

Reverse Conditional

Flatten Conditional

Combine/Split Conditional(s)