Operator Overloading in C#

Here is simple and easy example of operator overloading.

 using System;

class Rectangle
{
private int iHeight;
private int iWidth;

public Rectangle()
{
Height=0;
Width=0;
}
public Rectangle(int w,int h)
{
Width=w;
Height=h;
}

public int Width
{
get
{
return iWidth;
}
set
{
iWidth=value;
}
}
public int Height
{
get
{
return iHeight;
}
set
{
iHeight=value;
}
}

public int Area
{
get
{
return Height*Width;
}
}
/* OverLoading == */

public static bool operator==(Rectangle a,Rectangle b)
{
return ((a.Height==b.Height)&&(a.Width==b.Width));
}

/* OverLoading != */

public static bool operator!=(Rectangle a,Rectangle b)
{
return !(a==b);
}

/* Overloding > */

public static bool operator>(Rectangle a,Rectangle b)
{
return a.Area>b.Area;
}

/* Overloading < */
public static bool operator < (Rectangle a,Rectangle b)
{
return !(a > b);
}

/* Overloading >= */

public static bool operator >= (Rectangle a,Rectangle b)
{
return (a>b)||(a==b);
}

Continues…

Pages: 1 2

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!