c# - Equals is used. GetHashCode is not -


i have implemented class below:

public class carcomparer : iequalitycomparer<car>     {         public bool equals(car car1, car car2)         {                 if (car1 == null || car2 == null)                     return false;                  return (car1.description == car2.description);         }          public int gethashcode(car car)         {             unchecked              {                 int hash = 17;                 hash = hash * 29 + car.id.gethashcode();                 hash = hash * 29 + car.description.gethashcode();                 return hash;             }         }      } 

now see this:

car p1 = new car() { id = guid.newguid(), description = "test1" };         car p2 = new car() { id = guid.newguid(), description = "test1" };         car p3 = new car() { id = guid.newguid(), description = "test1" };         car p4 = new car() { id = guid.newguid(), description = "test1" };         var hash = new hashset<car>();         hash.add(p1);         hash.add(p2);          var hash2 = new hashset<car>();         hash2.add(p3);         hash2.add(p4);          var carcomparer = new carcomparer();         assert.that(hash, is.equivalentto(hash2).using(carcomparer)); 

i put breakpoints in .equals , .hashcode. equals used; gethashcode not. why?

you comparing 2 hashset using nunit is.equivalentto. there no reason call gethashcode - compares 2 collections equality of members. that's why gethashcode never called , equals called compare 2 items different hashsets equality. hashsets lists or other enumerable - doesn't change when comparing 2 collections.

you might expect gethashcode called when add item hashset - it's not so, because @ point carcomparer not yet known - don't pass hashset constructor. if this:

var hash = new hashset<car>(new carcomparer()); 

then gethashcode called when add new item corresponding hashset.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -