3

I assume that when doing a look-up in a dictionary it needs to hash the key you are giving it and then use that hash to find the object you are looking for.

If this is so, does using larger objects as keys slow down this look-up significantly or have other consequences that would not be encountered by using a string or simple data type as a key?

TruthOf42
  • 1,651
  • 3
  • 16
  • 34
  • Seems a bit smelly. What's the use case? – NWard Mar 24 '14 at 13:46
  • If the `GetHashCode` method of those objects is correctly implemented there shouldn't be any problem – Alberto Mar 24 '14 at 13:48
  • It's OK, but be careful with overriding GetHashCode() and Equals() methods – Dmitry Bychenko Mar 24 '14 at 13:49
  • Take a look at: http://stackoverflow.com/a/7941876/400760 – Jeffrey Charles Mar 24 '14 at 13:49
  • @jeffcharles that is a very good point!!! that should definitely go into any answer – TruthOf42 Mar 24 '14 at 13:51
  • It is not "bad", a string object is an excellent key. Or for that matter, an *object* object is a great key. You can't do better yourself. Trying to find the entry back with *another* object as the key, that's not so great. – Hans Passant Mar 24 '14 at 14:00
  • @NWard the specific use case is using that I want to loop through a bunch of controls on a page and then turn on/off another control mapped to that control in the loop. – TruthOf42 Mar 24 '14 at 14:25
  • @Alberto are you implying that a very large object should have no significant difference in runtime/processing vs string when it comes to GetHashCode? – TruthOf42 Mar 24 '14 at 14:30
  • 1
    @TruthOf42 It might be better to use an immutable, unique property of the controls as a key, rather than the whole object. – NWard Mar 24 '14 at 14:34
  • @NWard Yes, I think using the "Name" property will be what I'll use – TruthOf42 Mar 24 '14 at 14:35
  • @TruthOf42 It depends on the complexity of the `GetHashCode` method. If you are planning to use the `Name` property, just return `Name.GetHashCode()` – Alberto Mar 24 '14 at 14:43

1 Answers1

6

Yes, it's a bad idea to use a mutable object as a dictionary key.

Taking a look at https://stackoverflow.com/a/7941876/400760, leads me to believe there will be unintended consequences, even with a correctly implemented GetHashCode() based on how hash based collections are typically implemented.

It should be safe to use an immutable object as a dictionary key.

Community
  • 1
  • 1
Jeffrey Charles
  • 673
  • 5
  • 10