If I override Equals and GetHashCode, how do I decide which fields to compare? And what happens 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 Equal objects if they have the same MyId. Therefore, if Id is equal, but the description is different, they are still considered equal.
I just wonder what are the pitfalls of this approach? Of course, this design 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, the value is eq1, it will not be added. But this is the code that I control, but I wonder if there is code in the structure that can cause unforeseen problems?
So, should I always add all the public fields to my Equals () comparison, or what recommendations should I avoid unpleasant surprise due to a bad Framework-Mojo that was completely unexpected?
Michael stum
source share