Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding Equals() but not checking all fields - what will happen?
    primarykey
    data
    text
    <p>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?</p> <p>In other words, let's say I have this class:</p> <pre><code>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(); } } </code></pre> <p>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.</p> <p>I just wonder what the pitfalls of this approach are? Of course, a construct like this will behave as expected:</p> <pre><code> List&lt;EqualsTestClass&gt; test = new List&lt;EqualsTestClass&gt;(); 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); } </code></pre> <p>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?</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload