c# - Testing Collections of Objects for Equality using IEquatable<T> -


i have class have made implement iequatable<t> when i'm testing can compare ienumerable collections of objects using call such as:

assert.istrue(expected.sequenceequal(actual)); 

this working have few nagging doubts. class looks this:

public class thirdpartyclaim : iequatable<thirdpartyclaim> {     // fields removed question      public bool equals(thirdpartyclaim compareto)     {         if (object.referenceequals(this, compareto))         {            return true;         }          return this.claimid.equals(compareto.claimid) &&                 this.firstname.equals(compareto.firstname) &&                this.lastname.equals(compareto.lastname);     }     public override int gethashcode()    {               int hashclaimid = this.claimid == null ? 0 : this.claimid.gethashcode();         int hashfirstname = this.firstname == null ? 0 : this.firstname.gethashcode();         int hashlastname = this.lastname == null ? 0 : this.lastname.gethashcode();          return hashclaimid ^ hashfirstname ^ hashlastname;     } 

my understanding of overriding gethashcode() is used compare objects pointing same instance of class. extremely unlikely required on occasion (even in future).

is understanding correct , if so, can safely remove code?

is there better way compare collections of these objects in unit test?

although i'm constrained use mstest.

thans

overriding gethashcode required when override equals, otherwise hash-based containers might not work correctly. documentation of object.equals:

types override equals must override gethashcode; otherwise, hashtable might not work correctly.

even though code may not exercised in case, should keep anyway. in addition being correct, test equality of collections regardless of sequence:

assert.istrue(expected.except(actual).count() == 0);     

one change make gethashcode implementation eliminating symmetry: currently, switching around first , last name inside object lead making same hash code. sub-optimal. can combine multiple ints int hash code multiplying them small prime number, e.g. 31, , adding them up, this:

public override int gethashcode() {           int hashclaimid = this.claimid == null ? 0 : this.claimid.gethashcode();     int hashfirstname = this.firstname == null ? 0 : this.firstname.gethashcode();     int hashlastname = this.lastname == null ? 0 : this.lastname.gethashcode();      return 31*31*hashclaimid + 31*hashfirstname ^ hashlastname; } 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -