override Equals method : System Object Method « Development Class « C# / C Sharp






override Equals method

 


using System;

class Point: Object {
   protected int x, y;

   public Point() {
     this.x = 0;
     this.y = 0;
   }

   public Point(int X, int Y) {
      this.x = X;
      this.y = Y;
   }

   public override bool Equals(Object obj) {
      if (obj == null || GetType() != obj.GetType()) return false;
      Point p = (Point)obj;
      return (x == p.x) && (y == p.y);
   }

   public override int GetHashCode() {
      return x ^ y;
   }
}


class Point3D: Point {
   int z;

   public Point3D(int X, int Y, int Z) {
      this.x = X;
      this.y = Y;
      this.z = Z; 
   }

   public override bool Equals(Object obj) {
      return base.Equals(obj) && z == ((Point3D)obj).z;
   }

   public override int GetHashCode() {
      return base.GetHashCode() ^ z;
   }
}

class MyClass {

  public static void Main() {
     Point point2D = new Point(5, 5);
     Point3D point3Da = new Point3D(5, 5, 2);
     Point3D point3Db = new Point3D(5, 5, 2);

     if (!point2D.Equals(point3Da)) {
        Console.WriteLine("point2D does not equal point3Da.");
     }
     if (!point3Db.Equals(point2D)) {
        Console.WriteLine("Likewise, point3Db does not equal point2D.");
     }
     if (point3Da.Equals(point3Db)) {
        Console.WriteLine("However, point3Da equals point3Db.");
     }

  } 
}

   
  








Related examples in the same category

1.illustrates some of the System.Object class methodsillustrates some of the System.Object class methods
2.System Functions: LogOff, Restart, Shutdown, Hibernate, Standby
3.The Point class is derived from System.Object.
4.Object.Equals Method Determines whether the specified Object is equal to the current Object.
5.Build Equals method by using the Equals method from member variables
6.ValueType.Equals
7.Object.GetType Method Gets the Type of the current instance.
8.Object.MemberwiseClone Method Creates a shallow copy of the current Object.
9.Object.ReferenceEquals Method Determines whether the specified Object instances are the same instance.
10.Object.ToString Method Returns a String that represents the current Object.