Operator Overloading

Operators can be overloaded to provide more natural syntax for custom types. Operator overloading is most appropriately used for implementing custom structs that represent fairly primitive data types. For example, a custom numeric type is an excellent candidate for operator overloading.

The following symbolic operators can be overloaded:

+   -   *   /   ++   --   !   ~   %   &   |   ^
==  !=  <   <<  >>   >

Implicit and explicit conversions can also be overridden (with the implicit and explicit keywords), as can the literals true and false, and the unary + and - operators.

The compound assignment operators (e.g., +=, /=) are automatically overridden when you override the noncompound operators (e.g., +, /).

Operator Functions

An operator is overloaded by declaring an operator function. An operator function must be static, and 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 Note representing a musical note, and then overload the + operator:

public struct Note
{
  int value;

  public Note (int semitonesFromA)
   { value = semitonesFromA; }

  public static Note operator + (Note x, int semitones)
  {
    return new Note (x.value + semitones);
  }
}

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

Note B = new Note (2);
Note CSharp = B + 2;

Since we overrode +, we can use += too:

CSharp += 2;

Overloading Equality and Comparison Operators

Equality and comparison operators are often overridden when writing structs, and in rare cases ...

Get C# 5.0 Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.