Skip to content

Reject hex and binary NumberStyles in Parse and TryParse [patch] - #179

Merged
matt-edmondson merged 1 commit into
mainfrom
fix/177-reject-hex-binary-styles
Oct 30, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
fix/177-reject-hex-binary-styles

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #177

What was wrong

Parse(ReadOnlySpan<char>, NumberStyles, IFormatProvider?) never read AllowHexSpecifier or AllowBinarySpecifier. Input made only of decimal digits was read as decimal, so T.Parse("10", NumberStyles.HexNumber, …) returned 10 for PreciseNumber with no error. BigInteger returns 16 for the same call, and decimal and double throw.

The fix

The issue offered two options. This PR takes the one the triage recommended: refuse both styles with an ArgumentException, as decimal and double do. The check runs at the top of Parse. TryParse catches only FormatException and OverflowException, so it throws the same exception rather than returning false, which also matches decimal.TryParse.

NumberStyles.AllowBinarySpecifier only exists from .NET 8 onward. On the net7.0 target the mask uses its raw value (0x400), so a caller there who passes it is still refused.

Tests

ParseAndTryParse_RejectHexAndBinaryStylesAsDecimalDoes covers HexNumber, AllowHexSpecifier, BinaryNumber and AllowBinarySpecifier. For each one it checks that decimal.Parse throws, then asserts that PreciseNumber's string and span Parse, its string and span TryParse, and a generic INumberBase<T>.Parse all throw ArgumentException.

  • Without the fix, all 5 cases fail: four parse silently and "A" throws FormatException. With the fix they pass.
  • The full suite passes: 521/521 on net10.0. The solution builds for every target framework with no warnings.

Generated by Claude Code

Parse and TryParse never looked at AllowHexSpecifier or AllowBinarySpecifier,
so Parse("10", NumberStyles.HexNumber) read the digits as decimal and returned
10, with no error. Both styles now throw ArgumentException, as decimal and
double do, from Parse and TryParse alike.

Fixes #177

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

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit b2ce154 into main Oct 30, 2026
15 checks passed
@matt-edmondson
matt-edmondson deleted the fix/177-reject-hex-binary-styles branch October 30, 2026 02:49
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.

Parse("10", NumberStyles.HexNumber) silently returns 10 instead of 16 (or rejecting the style): AllowHexSpecifier and AllowBinarySpecifier are ignored

2 participants