3

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?

1
  • Some other remarks (your problem already been solved by answers). You should consider checking other for null in Equals. Since Person might be derived from (it is not a sealed class) also consider saying if (GetType() != other.GetType()) { return false; }. Note that your object is mutable (Name can be changed after object is constructed), and that mutable objects should not be mutated while contained in dictionaries or hash sets. Do override the virtual Object.Equals(object obj) by saynig return obj as Person;. Commented Aug 6, 2012 at 21:28

2 Answers 2

3

You need to make GetHashCode() get a case-*in*sensitive Hash Code at the moment, it will be a different hash code for upper and lower case Name's.

For example:

public override int GetHashCode() 
{ 
    return Name.ToUpperInvariant().GetHashCode(); 
} 
Sign up to request clarification or add additional context in comments.

2 Comments

ToUpperInvariant() would be more efficient than ToLower().
@m-y Thanks, I was just going from Memory, I knew there would be a better way.
2

Your GetHashCode() will return different hash codes for objects who should be considered identical.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.