Fix IReadOnlyDictionary DeepClone throwing InvalidCastException - #78
Merged
Merged
Conversation
The read-only dictionary overload passed the DeepClone method group to ToDictionary, which bound it to KeyValuePair and built a dictionary keyed by pairs, so the cast back to IReadOnlyDictionary failed on every call. Clone keys and values individually, as the IDictionary overload does, and add the missing null guard. Fixes #76 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q8KgDr8CfZLWPQ5o6nZdcV
|
This was referenced Sep 28, 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.



Fixes #76
What was wrong
DeepClone(this IReadOnlyDictionary<TKey, TValue>)passed theDeepClonemethod group toToDictionary. That bound it toDeepClone<KeyValuePair<TKey, TValue>>, so the method built a dictionary keyed by pairs. The cast back toIReadOnlyDictionary<TKey, TValue>then threwInvalidCastExceptionon every call, including on an empty dictionary.Change
IDictionaryoverload does.Ensure.NotNull(source)guard and documents theArgumentNullException.Tests
SpecializedCollectionTestsgains three tests:ReadOnlyDictionary_DeepClone_ShouldCreateIndependentCopychecks that values are independentIDeepCloneablecopies.ReadOnlyDictionary_DeepClone_Empty_ShouldReturnEmptyDictionaryReadOnlyDictionary_DeepClone_Null_ShouldThrowI checked the tests against the old code. With the fix reverted, the first two fail with the
InvalidCastExceptionfrom the issue. With the fix in place, the full suite passes, 36 of 36, on net10.0.Issue #77 also asks to keep the comparer and remove the ambiguity with
Dictionary<,>. This PR deliberately leaves that out.🤖 Generated with Claude Code
https://claude.ai/code/session_01Q8KgDr8CfZLWPQ5o6nZdcV
Generated by Claude Code