Question:

What is Operator Overloading in C# .net ?

Answer:

We had seen function overloading in the previous example. For operator Overloading, we will have a look at the example given below. We had defined a class rectangle with two operator overloading methods.

class Rectangle
{
 private int Height;
 private int Width;

 public Rectangle(int w,int h)
 {
   Width=w;
   Height=h;
 } 
 public static bool operator >(Rectangle a,Rectangle b)
 {
   return a.Height > b.Height ;
 }
 public static bool operator <(Rectangle a,Rectangle b)
 {
   return a.Height < b.Height ;
 } 
}

Let us call the operator overloaded functions from the method given below. When first if condition is triggered, the first overloaded function in the rectangle class will be triggered. When second if condition is triggered, the second overloaded function in the rectangle class will be triggered. 

public static void Main()
{
Rectangle obj1 =new Rectangle();
Rectangle obj2 =new Rectangle();

 if(obj1 > obj2)
 {
  Console.WriteLine("Rectangle1 is greater than Rectangle2");
 } 

 if(obj1 < obj2)
 {
  Console.WriteLine("Rectangle1 is less than Rectangle2");
 }
}

Keywords:

© 2017 QuizBucket.org