dotnet / dotnet/runtime

ToFrozenDictionary overloads differ in duplicate handling

Open
#127,798 4 comments 0 reactions 0 assignees View on GitHub
area-System.Collections help wanted
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

The [`KeyValuePair`-based `ToFrozenDictionary` overload](https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen.frozendictionary.tofrozendictionary?view=net-10.0#system-collections-frozen-frozendictionary-tofrozendictionary-2(system-collections-generic-ienumerable((system-collections-generic-keyvaluepair((-0-1))))-system-collections-generic-iequalitycomparer((-0)))) permits duplicates, letting the last value win. The method's remarks reflect that behavior.

However, the two overloads based on arbitrary (non-KVP) source do _not_ share this behavior.

Interestingly, their documentation _sort of_ reflects their current behavior, in that they _lack_ the special remark about duplicate handling. The absence is not easy to spot unless you are already aware.

The current situation is a bit of a trap. I switched my source from KeyValuePairs to ValueTuples (plus key and element selectors), and was caught off-guard by the behavioral change.

Also, while the documentation is technically correct, it is quite obscure that some overloads simply omit a remark about their duplicate handling. Ideally, each overload has an explicit remark - ideally all the same, but worst-case to warn of their differences.

### Reproduction Steps

```cs
new[] { KeyValuePair.Create(1, 1), KeyValuePair.Create(1, 2), }.ToFrozenDictionary(); // Pass
new[] { 1, 1 }.ToFrozenDictionary(key => key); // Fail
```

### Expected behavior

- The documentation is explicit about the duplicate handling for each overload.
- Ideally, all overloads have the same handling.

### Actual behavior

- The documentation says nothing about the duplicating handling on `TSource` overloads. The remark on the KeyValuePair-based overload easily misleads to the assumption that its behavior applies throughout.
- The `TSource`-based overloads throw on duplicates, whereas the KeyValuePair-based one lets the last duplicate win.

### Regression?

_No response_

### Known Workarounds

_No response_

### Configuration

_No response_

### Other information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.