Operator Overloading : Overloading Method : Class Interface C# Source Code


Custom Search

C# Source Code » Class Interface » Overloading Method »

 

Operator Overloading








    
 

using System;


public class Rectangle {
    public int width;
    public int height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public override string ToString() {
        return "width = " + width + ", height = " + height;
    }

    public static bool operator ==(Rectangle lhs, Rectangle rhs) {
        Console.WriteLine("In operator ==");
        if (lhs.width == rhs.width && lhs.height == rhs.height) {
            return true;
        } else {
            return false;
        }
    }

    public static bool operator !=(Rectangle lhs, Rectangle rhs) {
        Console.WriteLine("In operator !=");
        return !(lhs == rhs);
    }

    public override bool Equals(object obj) {
        Console.WriteLine("In Equals()");
        if (!(obj is Rectangle)) {
            return false;
        } else {
            return this == (Rectangle)obj;
        }
    }

    public static Rectangle operator +(Rectangle lhs, Rectangle rhs) {
        Console.WriteLine("In operator +");
        return new Rectangle(
          lhs.width + rhs.width, lhs.height + rhs.height);
    }

}
class MainClass {

    public static void Main() {

        Rectangle myRectangle = new Rectangle(1, 4);
        Console.WriteLine("myRectangle: " + myRectangle);
        Rectangle myRectangle2 = new Rectangle(1, 4);
        Console.WriteLine("myRectangle2: " + myRectangle2);

        if (myRectangle == myRectangle2) {
            Console.WriteLine(
              "myRectangle is equal to myRectangle2");
        } else {
            Console.WriteLine(
              "myRectangle is not equal to myRectangle2");
        }

        Rectangle myRectangle3 = myRectangle + myRectangle2;
        Console.WriteLine("myRectangle3: " + myRectangle3);
    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Class Interface
» Overloading Method