Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   Make Types Hashable with GetHashCode() (http://www.go4expert.com/forums/types-hashable-gethashcode-t21337/)

arunlalds 13Mar2010 15:09

Make Types Hashable with GetHashCode()
 
You almost always want to override GetHashCode(), especially with value
types, for performance reasons. Generating a hash value is generally done by
somehow distilling the data values in your class to an integer representation that is
different for every value your class can have. You should override GetHashCode()
whenever you override Equals().
Code:

public override int GetHashCode()
{
//note: This is just a sample hash algorithm.
//picking a good algorithm can require some
//research and experimentation
return (((int)_x ^ (int)_z) << 16) |
(((int)_y ^ (int)_z) & 0x0000FFFF);
}

Hash codes are not supposed to be unique for every possible set of values
your type can have. This is actually impossible, as you can deduce from the previous
code sample. For this reason, comparing hash values is not a good way to compute
equality.


All times are GMT +5.5. The time now is 21:50.