When overriding the Equals()
method, the MSDN recommends this:
class Point: Object {
protected int x, y;
public Point(int X, int Y) {
this.x = X;
this.y = Y;
}
public override bool Equals(Object obj) {
//Check for null and compare run-time types.
if (obj == null || GetType() != obj.GetType()) return false;
Point p = (Point)obj;
return (x == p.x) && (y == p.y);
}
}
But if we know that the subclass directly inherits from Object
, then is the following equivalent? Note the !base.Equals()
call:
class Point: Object {
protected int x, y;
public Point(int X, int Y) {
this.x = X;
this.y = Y;
}
public override bool Equals(Object obj) {
if (!base.Equals(obj) || GetType() != obj.GetType()) return false;
Point p = (Point)obj;
return (x == p.x) && (y == p.y);
}
}
In case this
reference is null
you are right, that the check can be (but does not seem to be guaranteed) superfluous, as can be seen in RuntimeHelpers.Equals
implementation quoted in this answer.
However, the !base.Equals(obj)
check will break your Equals
. When the references are not null
- !base.Equals
will also yield true
for any different references not only for null
values.
The scenario when it goes wrong is for example:
Point x = new Point(1,2);
Point y = new Point(1,2);
Console.WriteLine(x.Equals(y)); // will print 'False'
Even though x
and y
are equal in terms of your business logic, they are different objects so base.Equal
returns false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With