1. Home
  2. Docs
  3. C# Programming
  4. Operators
  5. Operator Overloading

Operator Overloading

operator overloading
C#

C# allows user-defined types to overload operators by defining static member functions using the operator keyword. Using operator overloading we can decide how to perform add, subtract, multiply, divide etc operations in our custom made stucts or classes. The following example illustrates an implementation of the + operator.

public class Complex
{
   public double Real { get; set; }
   public double Imaginary { get; set; }
}

Here above we have a complex class with real and imaginary property. lets create 2 or more objects of this complex and try to add them.

Complex a = new Complex() { Real = 1, Imaginary = 2 };
Complex b = new Complex() { Real = 1, Imaginary = 2 };
Complex c = new Complex() { Real = 1, Imaginary = 2 };

Now the question is how do we get the sum of 2 or 3 or more objects type of it. Usually we do it in this way

Complex sum = new Complex() { Real = a.Real + b.Real + c.Real, Imaginary = a.Imaginary + b.Imaginary + c.Imaginary };

Well this is the long way, How do we do it in short way? The key to this problem is by using the Operator Overloading. We introduce a new function in a Complex class to do it.

public static Complex operator +(Complex a, Complex b)
{
   return new Complex()
   {
      Real = a.Real + b.Real, 
      Imaginary = a.Imaginary + b.Imaginary
   }
}

Lets see the above code by disecting it.

public static Complex operator +(Complex a, Complex b)
  • The function should be static
  • Since, we need the Complex type as result, we need a return type “Complex”
  • Since we are using add operations, we are using “+”. We may use “-“, “*”, “/” as per our need
  • Since we need two operands to perform this, 2 objects as parameters are passed, the first one is the left operand (a) and the second one is the right operand (b) in “a + b”.
return new Complex()
{
   Real = a.Real + b.Real, 
   Imaginary = a.Imaginary + b.Imaginary
}

Since, we are returning the sum, we are adding real to the real and imaginary to imaginary

Using this now we will be able to use the logic to add 2 or more complex object in more easy way.

Complex sum = a + b + c;

The same goes with “-“, “*”, “/” operators

Easy right? isn’t it?

Was this article helpful to you? Yes No

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *