dotnet / dotnet/dotnet-api-docs
ReadOnlyDictionary Values and Keys collections are out of sync with KeyValuePairs
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
### Description
When underlying dictionary passed to a constructor of ReadOnlyDictionary is ConcurrentDictionary, all KeyValuePairs that are added to the ConcurrentDictionary after ReadOnlyDictionary is created are not visible through ReadOnlyDictionary.Values and ReadOnlyDictionary.Keys collection. However, ReadOnlyDictionary indexer and ContainsKey work correctly.
All of this is not a problem if regular Dictionary is used.
### Reproduction Steps
```
var dictionary = new ConcurrentDictionary();
dictionary["1"] = 1;
dictionary["2"] = 2;
dictionary["3"] = 3;
var readOnlyDictionary = new ReadOnlyDictionary(dictionary);
readOnlyDictionary.Values.Count.ShouldBe(dictionary.Count); // ok, count is 3
dictionary["4"] = 4;
readOnlyDictionary.ContainsKey("4").ShouldBeTrue(); // ok, key is present
readOnlyDictionary["4"].ShouldBe(dictionary["4"]); // ok, value is 4
readOnlyDictionary.Values.Count.ShouldBe(dictionary.Count); // fails, count is 3
```
### Expected behavior
Every KeyValuePair that is retrievable by ReadOnlyDictionary indexer. ContainsKey, TryGetValue... should also be present in Values and Keys collections. Everything should be in sync with underlying ConcurrentDictionary.
### Actual behavior
ReadOnlyDictionary's Values and Keys collections do not contain items that are added to underlying dictionary after creation of ReadOnlyDictionary if underlying dictionary is of type ConcurrentDictionary.
### Regression?
_No response_
### Known Workarounds
_No response_
### Configuration
.NET version is 6.0.400 running on Windows 10 21H1.
### Other information
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.