Mega Code Archive

 
Categories / C# / Development Class
 

Build Equals method by using the Equals method from member variables

using System; class Rectangle {    Point a, b;    public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY) {       this.a = new Point(upLeftX, upLeftY);       this.b = new Point(downRightX, downRightY);    }    public override bool Equals(Object obj) {       if (obj == null || GetType() != obj.GetType()) return false;       Rectangle r = (Rectangle)obj;       return a.Equals(r.a) && b.Equals(r.b);    }    public override int GetHashCode() {       return a.GetHashCode() ^ b.GetHashCode();    } } class Point {   private int x;   private int y;   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.GetHashCode() ^ y.GetHashCode();   } } class MyClass {    public static void Main() {       Rectangle r1 = new Rectangle(0, 0, 100, 200);       Rectangle r2 = new Rectangle(0, 0, 100, 200);       Rectangle r3 = new Rectangle(0, 0, 150, 200);       if (r1.Equals(r2)) {          Console.WriteLine("Rectangle r1 equals rectangle r2!");       }       if (!r2.Equals(r3)) {          Console.WriteLine("But rectangle r2 does not equal rectangle r3.");       }    } }