Operators can be overloaded to provide natural syntax for custom types.
The following symbolic operators can be overloaded:
+ (unary) - (unary) ! ? ++ -- + - * / % & | ^ << >> == != > < >= <=
The following operators are also overloadable:
The following operators are indirectly overloaded:
An operator is overloaded by declaring an operator function.
An operator function has the following rules:
In the following example, we define a struct called Money, and then overload the + operator:
struct Money { int value; public Money (int m) { value = m; } public static Money operator + (Money x, int anotherMoney) { return new Money (x.value + anotherMoney); } }
This overload allows us to add an int to a Money:
Money B = new Money (2);
Money myMoney = B + 2;
Overloading an operator automatically overloads the corresponding compound assignment operator.
In our example, since we overrode +, we can use += too:
myMoney += 2;
You can create operator functions with a single expression in expression-bodied syntax:
public static Money operator + (Money x, int anotherMoney) => new Money (x.value + anotherMoney);