Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Techniques of Operator Overloading in C#
1.2.
Syntax
1.3.
Unary Operators Overloading in C#
1.4.
Binary Operators Overloading in C#
1.5.
Benefits of Operator Overloading in C#
2.
FAQs
3.
Key Takeaways
Last Updated: Mar 27, 2024

Operator Overloading In C#

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this article, we will learn about operator overloading in C#. Overloading a function is a concept that can also be applied to operators. Operator overloading allows you to use the same operator for multiple tasks. When C# operators are applied to user-defined data types, it extends their capabilities. It allows for user-defined implementations of various operations in which one or both operands are of a user-defined class. Overloading is limited to the predefined set of C# operators.

Overloaded operators are functions that have unique names that begin with the operator keyword and end with the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

Let’s take an example to understand it. 

public static Room operator+ (Room b, Room c) {

   Room room= new Room();

   room.length = b.length + c.length;

   room.breadth = b.breadth + c.breadth;

   room.height = b.height + c.height;

   Return room;;

}

The above example implements the addition operator ( + ) for a user-defined class Room. It adds the attributes of two Room objects and returns the resultant  Room object.

Recommended topics, Palindrome in C# and, Unary operator overloading in c++.

Techniques of Operator Overloading in C#

In C#, operator overloading can be done using different operators' forms. Let's learn some operators and how they are used while overloading. The following table shows some operators' overloading ability (or overloadability of the operator).

Name of Operator 

Operators examples

Overloading ability

Unary Operators

+, -, !, ~, ++, – –

They take one operand and can be overloaded.

Binary Operators

+, -, *, /, %

They can be overloaded and takes two operands.

Conditional Logical Operators

&&, ||

They cannot be overloaded directly.

Comparison Operators

==, !=, =

They can be overloaded.

Assignment Operators

+=, -+, *=, /=, %=, =

The cannot be overloaded.

Syntax

The following is the syntax of operator overloading in the C# language.

public static className  operator op (parameters)  

{  

// Code  goes here

}

The syntax for operator overloading of Unary Operator  

public static className operator op (x)  

{  

// Code  goes here

}  

The following is the syntax of operator overloading of Binary operators.

  public static className operator op (x1, x2)  

{  

// Code  goes here

}  

Let’s learn Unary and Binary operator overloading in C# with multiple examples.

Unary Operators Overloading in C#

The following example explains how to overload unary operators in C#

Code:

using System;
namespace OperatorOverloading {

    class Calculator { // calculator class
    
     public int number1 , number2;
     public Calculator(int num1 , int num2)
     {
     number1 = num1;
     number2 = num2;
     }
    
        // following functions will perform operations by changing
        // the sign of integers
        public static Calculator operator -(Calculator c1)
        {
         c1.number1 = -c1.number1;
         c1.number2 = -c1.number2;
         return c1;
        }
    
        // function to display/print the numbers
        public void Print()
        {
         Console.WriteLine ("Num1 = " + number1);
         Console.WriteLine ("Num2 = " + number2);
        }
    }
    
    class TestingInMain
    {
    
     // Main Function or Driver code starts here
     static void Main(String []args)
     {
     
     // using overloaded - operator
     // with the class object
     Calculator calc = new Calculator(28, -12);
     
     calc = -calc;
     
     // printing the result
     calc.Print();
     }
        
    }
}

Output

Num1 = -28

Num2 = 12

The sign of the numbers is reversed in the above example of unary operator overloading in C#. Now let's learn binary operators overloading.

Binary Operators Overloading in C#

Since two operands are required for binary operators, two parameters will be passed to the function for binary operator overloading in C#. The following example explains how to implement binary operator overloading in C#.

Code:

using System;
namespace OperatorOverloading {

    class Calculator { // calculator class
    
     public int number = 0;
     
        // constructor with no-argument
        public Calculator() {}
         
         
        // parameterized constructor
        public Calculator(int n)
        {
            number = n;
        }
         
        // Overloading of Binary operator ("+")
        public static Calculator operator + (Calculator Cal1, Calculator Cal2)
        {
            Calculator Cal3 = new Calculator(0);
            Cal3.number = Cal2.number + Cal1.number;
            return Cal3; //returning the result of same type
        }
         
        // function to print result
        public void Print()
        {
            Console.WriteLine("{0}", number);
        }
    }
    
    class TestingInMain
    {
    
     // Main Function or Driver code starts here
     static void Main(String []args)
     {
     
     Calculator num1 = new Calculator(510);
            Calculator num2 = new Calculator(220);
            Calculator num3 = new Calculator();
             
            num3 = num1 + num2;
             
            num1.Print(); // Prints 510
            num2.Print(); // Prints 220
            num3.Print(); // Prints the result i.e. 730
     }
        
    }
}

Output:

510

220

730

In the above example, the result is 510+220, which is 730. Let's learn some benefits of operator overloading in C#.

Benefits of Operator Overloading in C#

The following are some benefits of operator overloading in C#:

  •  When C# operators are applied to user-defined data types, they gain additional capabilities because of operator overloading.
  • Operators can be thought of as compiler-internal functions.
  • The main benefit of operator overloading is that it allows us to integrate a new class type into our programming environment seamlessly.

This concludes operator overloading in C#. Now let’s move on to the FAQ section.

Also see, Ienumerable vs Iqueryable

FAQs

  1. What is Operator overloading?
    The method to assign more than one operation on the same operator is known as operator overloading.
  2. Can we overload comparison operators?
    Yes, we can overload comparison operators, but they can not be overloaded directly.
  3. What is a binary operator?
    A binary operator is an operator that takes two operands to perform operations.
  4. How many operands are there in unary operator overloading?
    As the name suggests, there is only one operand in unary operator overloading.
  5. What are access specifiers in C#
    Access specifier or modifier is the keyword used to specify the accessibility of a type and its members. The public, private, and internal access specifiers are mainly used in C#.

Also Read About - singleton design pattern in c#

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Key Takeaways

This article extensively discussed the operator overloading in C#. We learned the syntax of unary and binary operator overloading with multiple examples. We learned some operators of the C# language and their overloading ability.

If you are familiar with the C++ language, refer here to know more about operator overloading in C++.

We hope that this blog has helped you enhance your knowledge regarding operator overloading in C#, and if you would like to learn more, check out our articles in the code studio library. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Regular Expressions in C#
Next article
SOLID Principles in C#
Live masterclass