How to Overload Operator in C#

C# operators can be overloaded to do a different functionality altogether. This is called operator overloading in C#. Thus Operator overloading provide additional functionality to the operators. Note that not all operators can be over loaded. When an operator is overloaded, a functionality is added to the operator. This is done using the ‘operator’ keyword.
The syntax is as follows:
<access specifier> classname operator <operator>(parameters)

Step 1: Implementation

Operators may be considered as functions internal to the compiler. That is the expression a+b may be read as +(a, b) by the compiler. In the code below, the + operator is overloaded to subtract the values stored in the objects of the OverLoad class. The compiler interprets the statement as operator +(a, b), where the operator function of the first operand is invoked with the second operand of the operator.

Code – Operator Overloading

Step 2: Output

a and b are two objects of the class OverLoad. The statement a+b invokes the overloaded method for the + Operand. The output is as follows:


Step 3 – Operator Overloading

Overloading in C# is possible only for unary, binary and comparison operators. Some of the operators that can be overloaded are +, -, *, <, >, <=, ++. – and so on. The following table describes the overloading ability of the various operators available in C#:

Table – Operator overloading