Skip to content

Implement the non-generic IComparer on NaturalStringComparer [minor] - #75

Open
matt-edmondson wants to merge 1 commit into
mainfrom
fix/74-non-generic-icomparer
Open

matt-edmondson wants to merge 1 commit into
mainfrom
fix/74-non-generic-icomparer

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #74

What changed

NaturalStringComparer now implements System.Collections.IComparer as well as IComparer<string?>. Callers can pass it to ArrayList.Sort, Array.Sort(Array, IComparer), WPF's ListCollectionView.CustomSort, and the WinForms sorters without writing an adapter.

  • The new method is an explicit int IComparer.Compare(object?, object?) that forwards to the generic Compare. Null ordering and the ordinal tie-break therefore match the generic method.
  • Arguments that are neither strings nor null throw ArgumentException, as Comparer<T> does. A null paired with anything follows the generic null rules, which is also what Comparer<T> does.
  • The generic Compare is unchanged. Compare_AllocatesNothing still passes.
  • README and CLAUDE.md mention the interface.

Tests

There are four new tests in NaturalStringComparerTests:

  • ArrayList.Sort with a null element
  • Array.Sort(object[], IComparer), including a leading-zero tie
  • sign parity with the generic Compare over a grid of values that covers nulls, leading zeros, non-ASCII digits, and case
  • ArgumentException for non-string arguments

The tests look up the interface at run time. With the fix reverted they still build, and all 4 fail. With the fix applied, all 31 tests pass.

Package validation

dotnet pack -c Release still fails locally, but the CP* errors are the same 152 with and without this change. They are the Polyfill 11.4.5 shim drift tracked by #72, and #73 fixes them. Adding an interface introduces no new compatibility errors.


Generated by Claude Code

ArrayList.Sort, Array.Sort(Array, IComparer), WPF's CustomSort and the
WinForms sorters accept only System.Collections.IComparer, so callers had
to write their own adapter. An explicit IComparer.Compare now forwards to
the generic Compare, orders nulls the same way, and throws
ArgumentException for arguments that aren't strings, as Comparer<T> does.
The generic Compare is unchanged and still allocates nothing.

Fixes #74

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017vfJW3WL4nzXCqdxvXj85f
@sonarqubecloud

sonarqubecloud Bot commented Nov 2, 2026

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant