Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Overriding Equals using "as" and specialized Method for Correctness, Flexibility and Performance
    primarykey
    data
    text
    <p>I wondered about the best way to implement a <b>correct, flexible and fast Equals in C#, that can be used for practically any class and situation</b>. I figured that a specialized Equals (taking an object of the actual class as parameter) is needed for performance. To avoid code duplication, the general Equals ought to call the specialized Equals. Null checks should be performed only once, even in inherited classes.</p> <p>I finally came up with this design:</p> <pre><code> class MyClass { public Int32 SomeValue1 = 1; public Int32 SomeValue2 = 25; // Ignoring GetHashCode for simplicity. public override bool Equals(object obj) { return Equals (obj as MyClass); } public bool Equals(MyClass obj) { if (obj == null) { return false; } if (!SomeValue1.Equals (obj.SomeValue1)) { return false; } if (!SomeValue2.Equals (obj.SomeValue2)) { return false; } return true; } } class MyDerivedClass : MyClass { public Int32 YetAnotherValue = 2; public override bool Equals(object obj) { return Equals (obj as MyDerivedClass); } public bool Equals(MyDerivedClass obj) { if (!base.Equals (obj)) { return false; } if (!YetAnotherValue.Equals (obj.YetAnotherValue)) { return false; } return true; } } </code></pre> <p>Important ideas:</p> <ul> <li>Usage of the "as" operator. This way we don't have to check for nulls in the general Equals. Wrong class types get reduced to null and will be sorted out in the specialized Equals.</li> <li>Null check at exactly one point, even for derived classes.</li> <li>Checking the attributes one after another provides a clear structure.</li> </ul> <p>Are there flaws in this concepts, or did i miss any conditions?</p>
    singulars
    1. This table or related slice is empty.
    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