Hello,
I was reading “Guidelines for Overloading Equals() and Operator == (C# Programming Guide) <http://msdn2.microsoft.com/en-us/library/ms173147.aspx>”.
As a general rule should the derived.equals(base) yield true I guess if derived IS-A base then it should yield true
According to their example the answer is yes.
Thanks
Houman

Overriding equals
Sergey Kovalev
Hi, Houman
Actually, it is wrong logically. One thing can be cast into another one does not mean the thing is equal to the other. Especially, equal should always be each other like I have described above: "x.equals(y) must be same as y.equals(x)".
A derived class instance can be cast into the base class, that is because the type is compatible (cause the derived one have all the members of the base class, but reversely it cannot be compatible).
So, type compatibility and equality can't be mixed up.
Thank you
chub xbox
Thanks for the respones. If you follow thier example closely, here is what you'd get:
ThreeDPoint threeP = new ThreeDPoint(1,2,3);
TwoDPoint twoP = new TwoDPoint(1,2);
//initialize...
bool thisIsTrue = twoP.equals(threeP); //returns true because you can cast threeDPoint into a twoDPoint
bool thisIsFalse = threeP.equals(twoP); //returns false because you cannot cast twoDPoint into a threeDPoint
So doesn't that break the transitive rule
I think they need to check for the type instead of useing the cast 'as'. Am I missing something Or is their code wrong
Houman
DMottorn
Hi, Houman
In the example, it doesn't mean that derived class object equals base class object, you misunderstood anyway.
It just demo that derived class can call Equals method on the base class. But you must compare with all the members in derived class before you judge if the two object equals. In the case that the base class lacks some members which derived one have, the derived.equals(base) certainly should return false logically!
what I talking about above is in common condition, theoretically as long as you follow all the guarantees of Equals:
x.Equals(x) returns true.
x.Equals(y) returns the same value as y.Equals(x).
if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.
Successive invocations of x.Equals(y) return the same value as long as the objects referenced by x and y are not modified.
x.Equals(null) returns false.
You can surely implement one.
Thanks
Adminanup
Hi
i think what they meant is the following
public override bool Equals(System.Object obj)
{
//check equality on this class' fields
// return true if possible
if(...){return true;}
// if not resolved
//return base
return base.equals(obj);
}