C# – Overriding Equals() but not checking all fields – what will happen

cnet

If I override Equals and GetHashCode, how do I decide which fields to compare? And what will happen if I have two objects with two fields each, but Equals only checks one field?

In other words, let's say I have this class:

class EqualsTestClass
{
    public string MyDescription { get; set; }
    public int MyId { get; set; }

    public override bool Equals(object obj)
    {
        EqualsTestClass eq = obj as EqualsTestClass;
        if(eq == null) {
            return false;
        } else {
            return MyId.Equals(eq.MyId);
        }
    }

    public override int GetHashCode()
    {
        int hashcode = 23;
        return (hashcode * 17) + MyId.GetHashCode();
    }
}

I consider two objects Equal if they have the same MyId. So if the Id is equal but the description is different, they are still considered equal.

I just wonder what the pitfalls of this approach are? Of course, a construct like this will behave as expected:

        List<EqualsTestClass> test = new List<EqualsTestClass>();

        EqualsTestClass eq1 = new EqualsTestClass();
        eq1.MyId = 1;
        eq1.MyDescription = "Des1";

        EqualsTestClass eq2 = new EqualsTestClass();
        eq2.MyId = 1;
        eq2.MyDescription = "Des2";

        test.Add(eq1);
        if (!test.Contains(eq2))
        {
            // Will not be executed, as test.Contains is true
            test.Add(eq2);
        }

As eq2 is value-equal to eq1, it will not be added. But that is code that I control, but I wonder if there is code in the framework that could cause unexpected problems?

So, should I always add all public Fields in my Equals() Comparison, or what are the guidelines to avoid a nasty surprise because of some bad Framework-Mojo that was completely unexpected?

Best Answer

The reason for overriding Equals() is that you define, what it means for two instances to be equal. In some cases that means that all fields must be equal, but it doesn't have to. You decide.

For more information see the documentation and this post.

Related Topic