Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary<> and mutable keys

I was told that one of the many reasons strings were made immutable in the C# spec was to avoid the issue of HashTables having keys changed when references to the string keys altered their content.

The Dictionary<> type allows reference types to be used as a key. How does the dictionary avoid the issue of altered keys that lead to "misplaced" values? Is there a memberwise clone made of an object when used as a key?

like image 363
Pierreten Avatar asked Jun 09 '10 15:06

Pierreten


Video Answer


1 Answers

The Dictionary<TKey,TValue> type makes no attempt to protect against the user modifying the key used. It is purely left up to the developer to be responsible in not mutating the key.

If you think about this a bit this is really the only sane route that Dictionary<TKey,TValue> can take. Consider the implication of doing an operation like a memberwise clone on the object. In order to be thorough you'd need to do a deep clone because it will be possible for an object referenced in the key to also be mutated and hence affect the hash code. So now every key used in the table has it's full object graph cloned in order to protect against mutation. This would be both buggy and possibly a very expensive operation.

like image 196
JaredPar Avatar answered Oct 28 '22 06:10

JaredPar