C # redefining peers using the "how" and specialized method for correctness, flexibility and performance

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;

    // 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:

  • "as". , . Equals.
  • , .
  • .

, - ?

+3
1

Equals , :

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

:

if (GetType() != other.GetType())
{
    return false;
}

Object.Equals: "x.Equals(y) , y.Equals(x)". , , , .

+5

All Articles