Open In App

C# | Operator Overloading

Last Updated : 07 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Operators in C#

The concept of overloading a function can also be applied to operators. Operator overloading gives the ability to use the same operator to do various operations. It provides additional capabilities to C# operators when they are applied to user-defined data types. It enables to make user-defined implementations of various operations where one or both of the operands are of a user-defined class. Only the predefined set of C# operators can be overloaded. To make operations on a user-defined data type is not as simple as the operations on a built-in data type. To use operators with user-defined data types, they need to be overloaded according to a programmer’s requirement. An operator can be overloaded by defining a function to it. The function of the operator is declared by using the operator keyword

Syntax : 

access specifier  className  operator Operator_symbol (parameters)
{
    // Code
}

Note : Operator overloading is basically the mechanism of providing a special meaning to an ideal C# operator w.r.t. a user-defined data type such as structures or classes.

The following table describes the overloading ability of the various operators available in C# :  

Operators Description
+, -, !, ~, ++, – – unary operators take one operand and can be overloaded.
+, -, *, /, % Binary operators take two operands and can be overloaded.
==, !=, = Comparison operators can be overloaded.
&&, || Conditional logical operators cannot be overloaded directly
+=, -+, *=, /=, %=, = Assignment operators cannot be overloaded.

 Overloading Unary Operators

The return type can be of any type except void for unary operators like !, ~, + and dot (.) but the return type must be the type of ‘Type’ for – and ++ operators and must be a bool type for true as well as false operators. But do remember that the true and false operators can be overloaded as pairs only. The compilation error arises if a class declares one of these operators without declaring the other. 

The following syntax shows the use of Unary operator –  

operator (object); 
here, operator is a symbol that denotes a unary operator. 
operator a; 

Example :  

Input : 15, -25
Output : -15, 25

Input : -22, 18
Output : 22, -18 

C#




// C# program to illustrate the
// unary operator overloading
using System;
namespace Calculator {
     
class Calculator {
     
    public int number1 , number2;
    public Calculator(int num1 , int num2)
    {
        number1 = num1;
        number2 = num2;
    }
     
// Function to perform operation
// By changing sign of integers
public static Calculator operator -(Calculator c1)
{
    c1.number1 = -c1.number1;
    c1.number2 = -c1.number2;
    return c1;
}
 
// Function to print the numbers
public void Print()
{
    Console.WriteLine ("Number1 = " + number1);
    Console.WriteLine ("Number2 = " + number2);
}
}
 
class EntryPoint
{
     
    // Driver Code
    static void Main(String []args)
    {
         
        // using overloaded - operator
        // with the class object
        Calculator calc = new Calculator(15, -25);
         
        calc = -calc;
         
        // To display the result
        calc.Print();
    }
}
}


Output : 

Number1 = -15
Number2 = 25

Overloading Binary Operators

Binary Operators will work with two Operands. Examples of binary operators include the Arithmetic Operators (+, -, *, /, %), Arithmetic Assignment operators (+=, -+, *=, /+, %=) and Relational Operators etc. Overloading a binary operator is similar to overloading a unary operator, except that a binary operator requires an additional parameter. 

Syntax : 

operator operator (object1, object2); 
Here, second "operator" is a symbol that 
denotes a binary operator. 
operator + (a, b); 

Example :  

Input : 200, 40
Output : 240

Input : 300, 20 
Output : 320 

C#




// C# program to illustrate the
// Binary Operator Overloading
using System;
namespace BinaryOverload {
     
class Calculator {
     
    public int number = 0;
     
    // no-argument constructor
    public Calculator() {}
     
     
    // parameterized constructor
    public Calculator(int n)
    {
        number = n;
    }
     
    // Overloading of Binary "+" operator
    public static Calculator operator + (Calculator Calc1,
                                         Calculator Calc2)
    {
        Calculator Calc3 = new Calculator(0);
        Calc3.number = Calc2.number + Calc1.number;
        return Calc3;
    }
     
    // function to display result
    public void display()
    {
        Console.WriteLine("{0}", number);
    }
}
 
 
class CalNum {
     
    // Driver Code
    static void Main(string[] args)
    {
         
        Calculator num1 = new Calculator(200);
        Calculator num2 = new Calculator(40);
        Calculator num3 = new Calculator();
         
         
        num3 = num1 + num2;
         
        num1.display(); // Displays 200
         
        num2.display(); // Displays 40
         
        num3.display(); // Displays 240
         
    }
}
}


Output : 

200
40
240

Benefits of Operator Overloading : 

  • Operator Overloading provides additional capabilities to C# operators when they are applied to user-defined data types.
  • Operators may be considered as functions internal to the compiler.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads