Skip to content

Do not offer the MA0202 code fix to merge non-adjacent branches - #1580

Merged
meziantou merged 2 commits into
mainfrom
fix/ma0202-merge-adjacent-branches
Sep 23, 2026
Merged

meziantou merged 2 commits into
mainfrom
fix/ma0202-merge-adjacent-branches

Conversation

@meziantou

Copy link
Copy Markdown
Owner

What

The MA0202 code fix merges an #elif branch with the first earlier branch that has the same code, even when the two branches aren't next to each other. When a branch in between can also be active, the merge changes which code is compiled:

#if A
_ = 0;
#elif B
_ = 1;
#elif C // MA0202
_ = 0;
#else
_ = 2;
#endif

The fix produced #if (A) || (C) / _ = 0; / #elif B / _ = 1;. With B and C defined, the original code compiles _ = 1; and the fixed code compiles _ = 0;.

Fix

The code fix now merges a branch only with the branch right before it, when that branch has the same code. In the example above, no code fix is offered. For #if A / #elif B / #elif C where B and C have the same code, the fix gives #elif (B) || (C). Before, a third identical branch was merged into the first one. It is now merged into the adjacent one, which gives the same result.

The remove fix (#if / #else with 2 identical branches) only applies to adjacent branches, so it doesn't change. BranchGroup.FindPreviousDuplicateBranchIndex was only used by the fixer, so it is removed.

The analyzer still reports non-adjacent duplicates. The docs say that a branch with the same code as any previous branch is reported, and the existing NonAdjacentDuplicateBranch test covers this. The duplicated code can still be simplified by hand. The MA0202 docs now have a "Code fix" section that explains when the fix is offered.

I checked for other MA0202 work first: #1511 (nested conditionals) is merged and no MA0202 PR is open.

Tests

  • Added Fix_ElifElif_SameCode_MergesConditions and Fix_NonAdjacentElif_SameCode_NoCodeFix. The second one failed before the fix.
  • Ran ConditionalCompilationBranchesAreIdenticalAnalyzerTests on roslyn5.9 and roslyn4.8: 19/19 passed on each.

@meziantou
meziantou marked this pull request as ready for review September 23, 2026 04:45
Comment thread docs/Rules/MA0202.md Outdated
@meziantou
meziantou enabled auto-merge (squash) September 23, 2026 04:45
@meziantou
meziantou merged commit a234ad3 into main Sep 23, 2026
14 checks passed
@meziantou
meziantou deleted the fix/ma0202-merge-adjacent-branches branch September 23, 2026 04:49
This was referenced Sep 23, 2026
This was referenced Sep 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant