Dot Net For All

Operator Overloading in C#

Operator Overloading in C# Introduction

In this series of the articles, I am explaining about the different type of methods. In my previous article I have written about the constructors as methods. In this article I will discuss about the operator overloading in C#. There are many programming languages that support operator overloading.

The operator overloading has been introduced to give the logical meaning for the operations to a class. Though a class can have an Add method to add the instances of that particular class but, it would be much better to use the ‘+’ binary symbol to add as it denotes the operation itself.

The best example of the operator overloading in C# is the ‘+’ symbol. If it is used among the int variable type it ensure that we get the sum of the two variables but if it is used among the string variables , the two strings are concatenated.

It is not the CLR which works on operator overloading, it is the language specific compiler which helps the CLR to understand how it is going to behave with any particular operator. For Example the inequality operator in C# is ‘!=’ but in VB we use ‘<>’ for checking inequalities among operators.

Operator overload Method’s Syntax

Following is the list of all the operators which can be overloaded in a class or structure.

 

Apart from the above list following operators are also overload able:

 The following operators are indirectly overloaded:

I will use the below mentioned class as the reference to explain all the operators overloads.

public class Rectangle
    {
        private int length;
        private int breadth;

        public Rectangle(int length, int breadth)
        {
            this.length = length;
            this.breadth = breadth;
        }

        /// <summary>
        /// The function creates an Rectangle after adding the two provided rectangles(binary operator)
        /// </summary>      
        public static Rectangle operator +(Rectangle rect, Rectangle rect1)
        {
            return new Rectangle(rect.length + rect1.length, rect.breadth + rect1.breadth);
        }

        /// <summary>
        /// The function add the area of two rectangles provided.
        /// </summary>        
        public static int operator +(Rectangle area1, int area2)
        {
            return area1.Area() + area2;
        }

        /// <summary>
        /// The conditional operators
        /// </summary>        
        public static bool operator ==(Rectangle rect1, Rectangle rect2)
        {
            return (rect1.Area() == rect2.Area()) ? true : false;
        }

        public static bool operator !=(Rectangle rect1, Rectangle rect2)
        {
            return (rect1.Area() != rect2.Area()) ? true : false;
        }


        /// <summary>
        /// The function works on the same instance of the rectangle (unary operator)
        /// </summary>        
        public static Rectangle operator +(Rectangle rect1)
        {
            Rectangle tempRect = new Rectangle(1,1);
            tempRect.length = +rect1.length;
            tempRect.breadth =  +rect1.breadth;
            return tempRect;
        }
        
        public int Area()
        {
            return length * breadth;
        }

        public void DisplayArea()
        {
            Console.WriteLine(this.Area());
        }
    }

For the above class I have overloaded the operators to display the unary, binary and conditional operator overloads.

  1. Binary operators – Binary operators work in the cases where we have two operands. I have created two Rectangle instances in the code below and adding both of these instance to get a new instance which has the dimensions equals to the sum of already created rectangle as shown in the code below. I have overloaded the ‘+’ operator for the Rectangle class.
                Rectangle rect1 = new Rectangle(2, 2);           
                Rectangle rect2 = new Rectangle(2, 2);
    
                Rectangle rect3 = rect1 + rect2;
                rect3.DisplayArea();
    
  2. Unary operator – These are the operators which work only on the same operand and return the instance as shown in the code below
              Rectangle rectinst = new Rectangle(2, 2);
              rect3 = +rectinst;
              rect3.DisplayArea();
    
    
  3. Conditional Operator – I have overloaded the ‘==’ and ‘!=’ conditional operators to compare the dimensions of the two rectangle instances. We need to overload the consitional operators in pairs otherwise we will get the compile time error. For example we just cannot overload only one out of ‘==’ and ‘!=’ operator.
                Rectangle rect1 = new Rectangle(2, 2);           
                Rectangle rect2 = new Rectangle(2, 2);          
    
                if (rect1 == rect2)
                    Console.WriteLine("both rectangles have equal dimensions");
    
    
  4. Overloading the operator methods – Just like the instance methods we can overload the operator overload methods in the same class as you can see from the code snippet in part one where I have provided the operator overload method for ‘+’ operator twice.
    public static Rectangle operator +(Rectangle rect, Rectangle rect1)
            {
                return new Rectangle(rect.length + rect1.length, rect.breadth + rect1.breadth);
            }
    
            /// <summary>
            /// The function add the area of two rectangles provided.
            /// </summary>        
            public static int operator +(Rectangle area1, int area2)
            {
                return area1.Area() + area2;
            }
    
    

Thought operator overloading in C# is a very rarely used concept in C#. This concept is mainly used for the calculation intense applications like the financial ones, but it is a good to know concept in C#.Please let me know your thoughts about the article

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview