26 May 2013

Operator overloading in C# .NET

Operator overloading plays an important role in object oriented design. Operator overloading will be used to construct an object by combining other similar objects.

let’s consider an example on operator overloading to understand below :

  1. What is operator overloading?
  2. What the benefits of operator overloading?
  3. When to use operator overloading
  4. How to implement operator overloading

Code before using Operator Overloading:

public class Money
{
 public int Amount {get;set;}
}

public static void Main(string[]args]
{
   Money rentCost = new Money() {Amount = 30;};
   Money foodCost = new Money {Amount = 15};

  // Now requirement is to sum up the two costs.
  // One way is to sum up Amount of two costs and build 
  // another new instance of Money class
  int totalAmount = rentCost.Amount + foodCost.Amount;
  Money totalCost = new Money(){Amount = totalAmount};
}

The above code works as expected. But we have to repeat the code whenever we want to sum up two or more Money class objects. But when adding more than more than two objects, the code becomes difficult to read.

Implementing Operator overloading in C# .NET explained with an example:

public class Money
{
 public int Amount {get;set;}
 public static Money Operator +(Money moneyX, Money moneyY)
  {
   Money money = new Money(){
                Amount= moneyX.Amount + moneyY.Amount
        };
        return money;
  }
}
  1. The + operator has been overloaded for class.
  2. The method defining operator overloading, should always be static and public. Otherwise compiler error out with message "User defined operator must always be static and public".
  3. Similar to + operator overloading, you can overload minus, multiply, divide operators.
  4. Operator overloading allows explicit creation of new object using operations between related other two objects.

Using Operator overloading in C# .NET explained with an example:

public static void Main(string[]args]
{
  Money rentCost = new Money(){Amount = 30;};
  Money foodCost = new Money(){Amount = 15};
  Money travelCost = new Money()(Amount = 10};

  // Now getting total cost with 
  // operator overloading is much easier. 
  // Just add money class objects.
   Money totalCost = rentCost + foodCost;
  
   // Operator overloading can be used with 
   // more than two objects
   // Operator overloading helps in writing readable code
   totalCost = rentCost + foodCost + travelCost;
}

Advantages of operator overloading in C# .NET

  1. With operator overloading readability of the code improves.
  2. With operator overloading the code becomes explicit in nature, looking at the code fellow developers can easily guess what is going on.
  3. With operator overloading the code looks more conventional and becomes easy to follow.