Using a structure as a hashtable key

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am wondering if there is any problems with using a structure (contains 2
strings and 1 datetime) as a key to a hashtable. I have created one without
overriding the gethashcode or equals functions and it seems to work. However
i am not sure if occasionally this can cause a problem with uniqueness. The
examples i have seen all use classes and override the two functions mentioned
above. I may make the change from structure to class, but i want to be sure
i am making a gain by doing so. Thanks for any information on this.
 
I am wondering if there is any problems with using a structure (contains 2
strings and 1 datetime) as a key to a hashtable.

Assuming you're using the non-generic Hashtable class, it will cause a
lot of unnecessary boxing.

I have created one without
overriding the gethashcode or equals functions and it seems to work.

You should definitely override those and provide meaningful
implementations for types used as hash keys.


Mattias
 
Also, the object.GetHashCode is not guaranteed to be unique so you can run
into problems (that might be hard to debug) when a duplicate key is
generated.
 
Ok. Sounds like the better idea (more complete solution) is to use a class
intead of a structure and override the GetHashCode and Equals functions.
Thanks for the advise.

Peter Rilling said:
Also, the object.GetHashCode is not guaranteed to be unique so you can run
into problems (that might be hard to debug) when a duplicate key is
generated.
 
Peter Rilling said:
Also, the object.GetHashCode is not guaranteed to be unique so you can run
into problems (that might be hard to debug) when a duplicate key is
generated.

GetHashCode never has to be unique - and indeed if you have more than
one integer in your data, for instance, you *can't* make it unique.

So long as it returns the same value for equal objects, and so long as
Equals itself is correct, you shouldn't have problems.
 
Back
Top