Skip to content

IDE Actions 'Convert to switch statement' refactoring drops compound assignment (+=) when converting switch expression #60429

@masreplay

Description

@masreplay

Problem:
The VS Code "Convert to switch statement" refactoring incorrectly handles compound assignments (e.g., +=) when converting a switch expression to a switch statement.

Steps to Reproduce:

Original code with a switch expression in a compound assignment:

void main() {
  var x = 1;
  x += switch (x) { // += compound assignment
    1 => 2,
    2 => 3,
    _ => 4,
  };
  print(x); // Expected: 3 (1 + 2)
}

Apply the "Convert to switch statement" refactoring.

Resulting code loses the += and replaces it with direct assignment:

void main() {
  var x = 1;
  switch (x) { // += is lost
    case 1:
      x = 2; // Should be: x += 2;
    case 2:
      x = 3; // Should be: x += 3;
    default:
      x = 4; // Should be: x += 4;
  }
  print(x); // Actual: 2 (incorrect due to missing +=)
}

Expected Behavior:
The refactoring should preserve the compound assignment (+=), converting the switch expression into a statement that adds to x rather than reassigning it.

Impact:

The refactored code produces incorrect results because it discards the original value of x.

Developers must manually fix the issue after conversion.

Suggested Fix:
The refactoring tool should detect compound assignments (+=, -=, etc.) and ensure the switch statement preserves the operation.

Screenshots:
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2A bug or feature request we're likely to work onarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-assistIssues with analysis server assiststype-bugIncorrect behavior (everything from a crash to more subtle misbehavior)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions