If I add an object as the key to a collection, does the object have to meet any conditions? I read an article about immutability which stated the keys in a hashtable are immutable, amongst other things, hence this question.
Thanks
The key for a Dictionary can be mutable but changing it while it is stored in the Dictionary could be a very bad idea. If the key's hash value changes then the dictionary entry might be in the wrong bucket according to the key's new hash value. This means that you won't be able to find it again. From the documentation of Dictionary:
As long as an object is used as a key in the
Dictionary<TKey, TValue>, it must not change in any way that affects its hash value. Every key in aDictionary<TKey, TValue>must be unique according to the dictionary's equality comparer. A key cannot be null, but a value can be, if the value type TValue is a reference type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With