Using a structure as a hashtable key

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.
 
M

Mattias Sjögren

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
 
P

Peter Rilling

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.
 
G

Guest

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.
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top