Skip to content

Throw ArgumentException from Clamp when min is greater than max - #119

Merged
matt-edmondson merged 1 commit into
mainfrom
fix/clamp-inverted-range
Sep 27, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
fix/clamp-inverted-range

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #117

What changed

  • The instance Clamp<TNumber>(min, max) now throws ArgumentException (with paramName min) when min > max. It checks after converting both bounds, and the message follows the BCL's '{min}' cannot be greater than {max}.
  • The static INumber<T>.Clamp delegates to the instance method, so it gets the same check. Both carry <exception> docs.
  • Equal bounds are still accepted.

Before this change, PreciseNumber.Clamp(2, 3, 1) returned 3. Math.Clamp, decimal.Clamp and the default INumber<T>.Clamp all throw for an inverted range.

Tests

  • TestClampThrowsWhenMinIsGreaterThanMax covers a value inside the inverted range and a value outside it, through both the static and the instance overload.
  • TestClampAcceptsEqualBounds guards the min == max edge.

Verification

  • With the fix reverted, TestClampThrowsWhenMinIsGreaterThanMax fails. With the fix, it passes.
  • The full dotnet test suite passes: 387/387.

🤖 Generated with Claude Code

https://claude.ai/code/session_01M4xENzmZT4DZE8d5Hu6kEN


Generated by Claude Code

Clamp returned min for an inverted range, a value that satisfies
neither bound. Math.Clamp, decimal.Clamp and the default
INumber<T>.Clamp all throw, so generic code behaved differently
depending on T.

Fixes #117

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

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit 6fafe87 into main Sep 27, 2026
12 checks passed
@matt-edmondson
matt-edmondson deleted the fix/clamp-inverted-range branch September 27, 2026 00:20
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.

Clamp(value, min, max) returns min when min > max instead of throwing ArgumentException

2 participants