Skip to content

ReadOnlyDictionary Values and Keys collections are out of sync with KeyValuePairs #8338

Open
@ante-maric

Description

@ante-maric

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<string, int>();
        dictionary["1"] = 1;
        dictionary["2"] = 2;
        dictionary["3"] = 3;
        var readOnlyDictionary = new ReadOnlyDictionary<string, int>(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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions