Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net 3.5 List<T> Equality and GetHashCode

I'm implementing IEquatable in a custom class that has a List<T> as a property, like so:

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'm concerned about the List while trying to implement the Equals and GetHashCode methods. Specifically, will List<T>.Equals evaluate the equality of it's contents? Likewise for List<T>.GetHashCode?

like image 590
Hc5kphUXpR Avatar asked Dec 22 '22 06:12

Hc5kphUXpR


1 Answers

Nope .Equals will just do a Reference comparison and GetHashCode will return the standard code allocated per object.

If you want to perform .Equals base on the content of the list you'll have to enumerate over it yourself, like wise with generating a hash code.

like image 89
AnthonyWJones Avatar answered Jan 04 '23 22:01

AnthonyWJones