In Microsoft's MSDN Library article on Object.Equals
Method (Object), (http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx) an example is presented to demonstrate how to override Equals. It looks like this:
class Point
{
... // IEquatable<Point> is not implemented.
public override bool Equals(Object obj)
{
//Check for null and compare run-time types.
if ((obj == null) || ! this.GetType().Equals(obj.GetType())) {
return false;
}
else {
Point p = (Point) obj;
return (x == p.x) && (y == p.y);
}
}
}
sealed class Point3D: Point
{
int z;
public override bool Equals(Object obj)
{
Point3D pt3 = obj as Point3D;
if (pt3 == null)
return false;
else
return base.Equals((Point)obj) && z == pt3.z; // Here!!!
}
}
In the ensuing documentation, my attention was drawn to the following statement.
(If it is a Point3D
object, it is cast to a Point
object and passed to the base class implementation of Equals
.)
Here, return base.Equals((Point)obj)
why bother casting obj into Point
?
Update:
I guess it might just be a typo, as I check the .NET 4.0 version document, it is a one-liner:
return base.Equals(obj) && z == ((Point3D)obj).z