Does the key that I use for the collection use to satisfy any requirements?

If I add an object as a key to the collection, should the object meet any conditions? I read an article on immutability, which stated that keys in a hash table are immutable, among other things, so this is the question.

thank

+3
source share
3 answers

The key for a dictionary can be volatile, but changing it while it is stored in the dictionary can be a very bad idea. If the hash key value is changed, the dictionary entry may be in the wrong bucket according to the hash key value. This means that you cannot find it again. From the Dictionary documentation :

Dictionary<TKey, TValue>, - -. Dictionary<TKey, TValue> . null, , TValue .

+4

, . .

:

Dictionary<Car, Color>

Car , ( Hash as Mark).

0

, , . .

: " ". , " " - , - . ( , .NET docs " " . OO - , .)

, , , . , . . ; "", . , , "" .

, - "": , . , , , , . . : "" ; , .

, , " " "".

" ", Equals GetHashCode. Equals true, . GetHashCode ; "", -.

If they are “objects,” implementations Equalsand GetHashCodethat you inherit from System.Object will use reference equality to determine if the two objects are “the same” (and therefore should be treated as the same key in the dictionary) that you want. Thus, until you inherit something that itself overrides Equalsand GetHashCodeyou do not need to do anything special to use the "object" as a key.

0
source

Source: https://habr.com/ru/post/1780781/


All Articles