.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Visual Studio >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Operator Overloading

Posted By:SanthoshNathan       Posted Date: November 02, 2010    Points: 15    Category: Visual Studio    URL: http://www.dotnetspark.com  

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(14);
        Console.WriteLine("myRectangle: " + myRectangle);
        Rectangle myRectangle2 = new Rectangle(14);
        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);
    }
}


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend