I wondered about the best way to implement a correct, flexible and fast Equals in C#, that can be used for practically any class and situation. 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.
I finally came up with this design:
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;
}
}
Important ideas:
Are there flaws in this concepts, or did i miss any conditions?
Your Equals method isn't reflexive when different types are involved:
MyDerivedClass mdc = new MyDerivedClass();
MyClass mc = new MyClass();
Object omdc = mdc;
Object omc = mc;
// mc.Equals(mdc) - true
// mdc.Equals(mc) - true by calling the right overload
// omc.Equals(omdc) - true
// omdc.Equals(omc) - false, the "as" in MyDerivedClass will result in null
The normal way round this is to use:
if (GetType() != other.GetType())
{
return false;
}
See the docs in Object.Equals: "x.Equals(y) returns the same value as y.Equals(x)." Relying on overloading to give different results could end up with horribly issues which would be very subtle to debug.