Consider a class
class MyClass {
int fieldA;
int fieldB;
public override bool Equals(object obj) {
if (this == obj)
return true;
if (!(obj is MyClass))
return false;
MyClass other = obj as MyClass;
return fieldA == other.fieldA || fieldB == other.fieldB;
}
}
Two MyClass should be equal when fieldA is equal or fieldB is equal.
Now, I can't find a good GetHashCode() implementation that matches the Equals method I've written. Without reference to other MyClass object to compare to, getting the same hashcode looks like an impossible task, unless I set hashcode to same value and deal with hash collision.
I've written a test case that arbitrarily sets MyClass1 and MyClass2.
for (int a1 = 0; a1 \< 3; a1++) {
for (int b1 = 0; b1 \< 3; b1++) {
MyClass myClass1 = new MyClass { fieldA = a1, fieldB = b1 };
for (int a2 = 0; a2 \< 3; a2++) {
for (int b2 = 0; b2 \< 3; b2++) {
MyClass myClass2 = new MyClass { fieldA = a2, fieldB = b2 };
bool equals = myClass1.Equals(myClass2);
bool hashEquals = myClass1.GetHashCode().Equals(myClass2.GetHashCode());
if (equals != hashEquals)
Console.WriteLine($@"Comparing ({a1}, {b1}) with ({a2}, {b2}). Equals: {equals}. HashCode: {hashEquals}");
}
}
}
}
If GetHashCode is written properly, there shouldn't be any case where equals != hashEquals
hence, nothing should be printed.
I've tried setting HashCode to one of the fields, but realized if another field matches, hashcode would be different.