Repository navigation
Fix HashSet.TryGetValue throwing for null with a StringComparer - #628
Merged
Merged
Conversation
This was referenced Oct 12, 2026
This was referenced Oct 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Bug
The
HashSet<T>.TryGetValuepolyfill (active below net472) calledcomparer.GetHashCodeon the lookup value and on every element of the set.HashSet<T>itself never passesnullto the comparer'sGetHashCode, so with a comparer such asStringComparer.OrdinalIgnoreCasethe polyfill threwArgumentNullExceptionwhen the lookup value wasnull, or when the set containednull. It was also O(n) with a hash computed per element, even for a value that is not in the set.Fix
Use
Containsfirst, which is a hashed lookup and handlesnullthe way the set does. Only when the value is present, scan for the stored instance usingcomparer.Equalsalone (which is what the set itself calls for anullentry).Test
TryGetValue_NullWithStringCompareruses anOrdinalIgnoreCaseset containingnull, and checks a case-insensitive hit returns the stored instance, anulllookup succeeds, a miss returns false, and anulllookup on a set withoutnullreturns false. It threwArgumentNullExceptionon net462 before the fix, and passes on net462 (polyfill), net48 and net10.0 (BCL).