Right way to implement GetHashCode for this struct

前端 未结 7 1870
庸人自扰
庸人自扰 2021-02-13 06:13

I want to use a date range (from one date to another date) as a key for a dictionary, so I wrote my own struct:

   struct DateRange
   {
      public DateTime St         


        
7条回答
  •  星月不相逢
    2021-02-13 06:46

    Something like this:) with a different prime number:)

    public override int GetHashCode()
    {
        unchecked  
        {
            int hash = 23;
            // Suitable nullity checks etc, of course :)
            hash = hash * 31 + Start.GetHashCode();
            hash = hash * 31 + End.GetHashCode();
            return hash;
        }
    }
    

    This is not the fastest implementation but it produces a good hash code. Joshua bloch indicates that as well and you also calculate the performance, ^ is usually faster. correct me if i m wrong.

    See Jon Skeets impl for c# :

提交回复
热议问题