Overriding Equals (): redundant null comparison when calling base.Equals ()?

When overriding the Equals() method, 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 == px) && (y == py); } } 

But if we know that a subclass directly inherits from Object , then is the next equivalent ? Pay attention to the call !base.Equals() :

 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 == px) && (y == py); } } 
+6
source share
1 answer

In case this reference is null , you are right that the verification may be (but does not seem guaranteed) unnecessary, as can be seen from the implementation of RuntimeHelpers.Equals mentioned in this answer .

However, checking !base.Equals(obj) will break your Equals . When links are not null - !base.Equals will also give true for any different links, not just null values.

A scenario when it goes wrong, for example:

 Point x = new Point(1,2); Point y = new Point(1,2); Console.WriteLine(x.Equals(y)); // will print 'False' 

Even if x and y are equal in terms of your business logic, they are different objects, so base.Equal returns false .

+5
source

All Articles