I wondered about the best way to implement the right, flexible and fast Equals in C #, which can be used for almost any class and situation . I realized that performance requires specialized Equals (taking an object of the actual class as a parameter). To avoid code duplication, general Equals should call specialized Equals. Zero checks should only be performed once, even in legacy classes.
I finally came up with this design:
class MyClass
{
public Int32 SomeValue1 = 1;
public Int32 SomeValue2 = 25;
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:
, - ?