Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
   }
}
like image 964
kdbanman Avatar asked Jul 20 '15 23:07

kdbanman


1 Answers

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.

like image 150
BartoszKP Avatar answered Sep 30 '22 17:09

BartoszKP