Replies: 2 comments 2 replies
-
IMO, it's understandable for it to work that way, but it is surprising. I'd argue it's a documentation bug then, but that's just me. https://github.com/dotnet/dotnet-api-docs/blob/main/xml/System.Collections.Generic/Dictionary%602+KeyCollection.xml |
Beta Was this translation helpful? Give feedback.
-
I beg to differ. From the documentation of the KeyCollection's
By the same reasoning, any collection type that allows using a user-defined comparator for managing its items (like a HashSet or SortedSet, for example) shouldn't make sense to you either, as these in the same manner can "contain" values that a copy of it doesn't "contain" anymore... |
Beta Was this translation helpful? Give feedback.
-
Today I came to a surprise writing a unit test to verify some keys are present in my dictionary and some are not. The surprising part was that when I searched for a key that the
Keys
did not contain*, it turned out it contained it. The asterisk is there because I usedStringComparer.OrdinalIgnoreCase
for the dictionary. Here's the essence of my code:If I called
Dictionary.ContainsKey
, I wouldn't be surprised by this result, because I chose the comparer explicitly. But when I use the Keys collection, I do not expect it to be aware of the comparer, and nothing in the public documentation of theDictionary<Tk,Tv>.KeyCollection
class says that it is. Only after hitting this result, and then checking the source code of that class I realized why it works that way.Now I kind of wonder if this is by design. If so, I believe the documentation should contain at least some hint that
Keys
property is aware of the comparer. Although, again, by explicitly adding keys to the dictionary, and then checking what I added, I still do not expect the comparer to be in play.Beta Was this translation helpful? Give feedback.
All reactions