CSharp/C# Tutorial - C# Operator Overloading






Operators can be overloaded for custom types.

The following symbolic operators can be overloaded:


+(unary) //  w w w  .  j a  v a  2s .co m
-(unary) 
! 
~
++
--
+ 
-
*
/
% 
& 
|
^
<<
>> 
== 
!=
>
<
>= 
<=

The following operators are also overloadable: Implicit and explicit conversions true and false.

The compound assignment operators (e.g., +=, /=) are implicitly overridden by overriding the noncompound operators (e.g., +, /).

The conditional operators && and || are implicitly overridden by overriding the bitwise operators & and |.





Operator Functions

An operator is overloaded by declaring an operator function.

The name of the function is specified with the operator keyword followed by an operator symbol.

The operator function must be marked static and public.

The parameters of the operator function represent the operands.

The return type of an operator function represents the result of an expression.

At least one of the operands must be the type in which the operator function is declared.

In the following example, we define a struct called Coin and then overload the + operator:


public struct Coin {
    int value;
    public Coin (int c) {
       value = c;
    }
    public static Coin operator + (Coin x, int p) {
       return new Coin (x.value + p);
    }
}

This overload allows us to add an int to a Coin:


Coin B = new Coin (2);
Coin A = B + 2;

Overloading an assignment operator automatically supports the corresponding compound assignment operator.

In our example, since we overrode +, we can use += too:


B += 2;




Note

The C# compiler enforces operators that are logical pairs to both be defined. These operators are (== !=), (< >), and (<= >=).

If you overload == and !=, you will usually need to override the Equals and GetHashCode methods defined on object.

If you overload (< >) and (<= >=), you should implement IComparable and IComparable<T>.

Implicit and explicit conversions are overloadable operators.