Skip to content

Fix MA0002 false positive on [with(StringComparer.Ordinal)] collection expression - #1237

Merged
meziantou merged 2 commits into
mainfrom
meziantou-ma0078-with-syntax-dictionary-support
Jul 27, 2026
Merged

meziantou merged 2 commits into
mainfrom
meziantou-ma0078-with-syntax-dictionary-support

Conversation

@meziantou

Copy link
Copy Markdown
Owner

Fixes #1235

Problem

Dictionary<string, List<string>> duplicates = [with(StringComparer.Ordinal)]; was incorrectly flagged by MA0002 ("IEqualityComparer or IComparer is missing").

Root Cause

AnalyzeCollectionExpression checked Elements.Length == 0 but did not check ConstructArguments (C# 15's with(...) arguments).

In Roslyn's IOperation model for [with(StringComparer.Ordinal)]:

  • Elements.Length == 0 (no key-value entries) → check passes
  • ConstructArguments.Length == 1 (the StringComparer.Ordinal) → was not checked

So the analyzer continued and incorrectly reported MA0002.

Fix

Under #if ROSLYN_5_6_OR_GREATER (when C# 15's with(...) syntax is available), check ConstructArguments for an existing IEqualityComparer<string> or IComparer<string>. If already present, skip reporting.

Tests added

  • [with(StringComparer.Ordinal)] → no diagnostic ✓
  • [with(10)] (capacity only, no comparer) → still reports MA0002 ✓

meziantou and others added 2 commits July 27, 2026 10:28
…ring comparer

When using C# 15's `with(...)` syntax in a collection expression,
e.g. `Dictionary<string, int> d = [with(StringComparer.Ordinal)]`,
MA0002 was incorrectly reported because AnalyzeCollectionExpression
only checked `Elements.Length == 0` and not `ConstructArguments`.

Fix: Under ROSLYN_5_6_OR_GREATER, check whether ConstructArguments
already contains a string comparer (IEqualityComparer<string> or
IComparer<string>) and skip reporting in that case.

Closes #1235

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@meziantou
meziantou merged commit 8d9d080 into main Jul 27, 2026
14 checks passed
@meziantou
meziantou deleted the meziantou-ma0078-with-syntax-dictionary-support branch July 27, 2026 08:41
This was referenced Jul 27, 2026
This was referenced Sep 3, 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.

"with" syntax and Dictionaries

1 participant