CSharp - Type Creation Operator Overloading

Introduction

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:

  • Implicit and explicit conversions (with the implicit and explicit keywords).
  • The true and false operators (not literals).

The following operators are indirectly overloaded:

  • 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.

An operator function has the following rules:

  • The name of operator 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 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);

Related Topics