Sample MSDN code: why is it executed before calling base.Equals (object)?

An article in the Microsoft MSDN library on the Object.Equals method (object), ( http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx ) provides an example that demonstrates 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 == px) && (y == py); } } } 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 following documentation, my attention was drawn to the following statement.

(If it is a Point3D object, it is transformed into a Point object and passed to the implementation of the base class Equals .)

Here, return base.Equals((Point)obj) why worry about return base.Equals((Point)obj) obj to Point ?

Update:

I assume this may be a typo, as I am checking a .NET 4.0 version document, this is single-line:

 return base.Equals(obj) && z == ((Point3D)obj).z 
+4
source share
3 answers

It makes no sense (ha ha) to pour obj in Point . You are correct that the Point.Equals method Point.Equals also pass it to Point . This is redundant.

0
source

When equality checking is required, it is recommended today to implement a common IEquatable<T> common interface. Its Equals(T) method provides type safety and prevents boxing / unpacking overhead for value types.

If the Point class implements the IEquatable<Point> interface, it will contain an overload of the Equals(Point) method, which is more efficient for calling than Equals(Object) . A plausible excuse is that the cast-type before Point is pre-executed if the interface is implemented.

 class Point : IEquatable<Point> { public Equals(Point other) { return other != null && this.x == other.x && this.y == other.y; } public override bool Equals(Object obj) { return this.Equals(obj as Point); } } 
+1
source

In the Point class, we compare types:

 this.GetType().Equals(obj.GetType()) 

Point type is not equal to Point3D.

0
source

Source: https://habr.com/ru/post/1490584/


All Articles