I have the following simple class
public class Person : IEquatable<Person>
{
public bool Equals(Person other)
{
return Name.Equals(other.Name, StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
public Person(string name)
{
Name = name;
}
public string Name { get; set; }
}
Now I am creating an array of persons, calling distinct on them and pass the default Equality Comparer, which is the one implemented by IEquatable<Person>
var persons = new[] {new Person("foo"), new Person("Foo"), new Person("bar"), new Person("Bar")};
persons.Distinct(EqualityComparer<Person>.Default);
When I inspect the distincted persons, I am expecting an IEnumerable<Person> containing foo, bar. However the contents are foo, Foo, bar, Bar
When I initialize the List with foo, foo, bar, bar the result is as expected. So it seems to me as if StringComparison.InvariantCultureIgnoreCase in the Person.Equals method is ignored.
Has anyone an idea?
otherfornullinEquals. SincePersonmight be derived from (it is not asealedclass) also consider sayingif (GetType() != other.GetType()) { return false; }. Note that your object is mutable (Namecan be changed after object is constructed), and that mutable objects should not be mutated while contained in dictionaries or hash sets. Do override the virtualObject.Equals(object obj)by saynigreturn obj as Person;.