1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Make Types Hashable with GetHashCode()

Discussion in 'C#' started by arunlalds, Mar 13, 2010.

  1. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    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.
     

Share This Page