Table of contents
1.
Introduction
2.
Techniques of Operator Overloading in C#
3.
Syntax of operator overloading in the C#
4.
Unary Operators Overloading in C#
4.1.
C#
5.
Binary Operators Overloading in C#
5.1.
C#
6.
Benefits of Operator Overloading in C#
7.
Frequently Asked Questions
7.1.
What is Operator overloading?
7.2.
Which operators are not overloaded in C#?
7.3.
What is operator overloading vs overriding in C#?
7.4.
Can comparison operators be overloaded in C#?
7.5.
What are access specifiers in C#
8.
Conclusion
Last Updated: Oct 7, 2024

Operator Overloading In C#

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

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.

Operator Overloading In C#

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 of operator overloading in the C#

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:

  • C#

C#

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:

  • C#

C#

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.

 

Also see, Ienumerable vs Iqueryable

Frequently Asked Questions

What is Operator overloading?

The method to assign more than one operation on the same operator is known as operator overloading.

Which operators are not overloaded in C#?

In C#, operators that cannot be overloaded include assignment (=), member access (.), conditional logical (&&, ||), ternary conditional (?:), null coalescing (??), is, as, sizeof, typeof, nameof, checked, unchecked, new, and default.

What is operator overloading vs overriding in C#?

Operator overloading allows defining custom behavior for operators in C#, while overriding involves providing new implementations for methods in derived classes, using polymorphism principles.

Can comparison operators be overloaded in C#?

Yes, comparison operators like ==, !=, <, >, <=, and >= can be overloaded in C#. This allows custom comparison logic for user-defined types to match specific application needs.

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#.

Conclusion

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.

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 Code360

Live masterclass