Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 692
GurdeepS Avatar asked Dec 01 '25 05:12

GurdeepS


1 Answers

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 a Dictionary<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.

like image 145
Mark Byers Avatar answered Dec 03 '25 20:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!