C# | Operator Overloading
Last Updated :
07 Aug, 2021
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.
Similar Reads
Perl | Operators | Set - 1
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their
12 min read
C# Operators
In C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C++ | Nested Ternary Operator
Ternary operator also known as conditional operator uses three operands to perform operation. Syntax : op1 ? op2 : op3; Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : ca ? b: c ? d : e ? f : g ? h : ia ? b ? c : d : e Let us unde
5 min read
Unary Operators in C
In C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
Operators in C++
C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Ruby | Operators
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Ruby as follows: Arithmetic
11 min read
unordered_multimap operator= in C++
The unordered_multimap::operator= is a built-in function in C++ STL which does three types of tasks which are explained below. Syntax (copying elements from different container) : unordered_multimap_name1 operator= (unordered_multimap_name2)Parameters: The function does not accepts any parameter. Th
4 min read
list::operator= in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::operator= This operator is used to assign n
2 min read
match_results operator= in C++
The match_results::operator= is used to replace all the matches in a smatch object with new matches from another smatch object.Syntax: smatch_name1 = (smatch_name2) Note: smatch_name is an object of match_results class. Parameters: The smatch object on the right side gets copied to the one at the le
2 min read
Operator overloading in C++ to print contents of vector, map, pair, ..
Operator overloading is one of the features of Object oriented programming which gives an extra ability to an operator to act on a User-defined operand(Objects). We can take advantage of that feature while debugging the code specially in competitive programming. All we need to do is to overload the
3 min read