.net 3.5 List <T> Equality and GetHashCode

I implement IEquatable in a custom class that has a List <T> property as a property:

 public class Person { public string FirstName { get; set; } public string LastName { get; set; } public List<string> Dislikes; public bool Equals(Person p) { if (p == null) { return false; } if (object.ReferenceEquals(this, p)) { return true; } return this.FirstName == p.FirstName && this.LastName == p.LastName && this.Dislikes == p.Dislikes; //or this.Dislikes.Equals(p.Dislikes) } public override int GetHashCode() { int hash = 17; hash = hash * 23 + (this.FirstName ?? String.Empty).GetHashCode(); hash = hash * 23 + (this.LastName ?? String.Empty).GetHashCode(); hash = hash * 23 + this.Dislikes.GetHashCode(); return hash; } } 

I am worried about List when trying to implement the Equals and GetHashCode methods. In particular, will List <T> .Equals evaluate the equality of its contents? Similarly for List <T> .GetHashCode?

+4
source share
1 answer

No .Equals will simply compare the links, and GetHashCode will return the standard code allocated for each object.

If you want to execute the .Equals database in the contents of the list, you will have to list it yourself, for example, with the creation of a hash code.

+11
source

All Articles