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 overloadable symbolic operators are as follows:

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

The following operators are also overloadable:

  • Implicit and explicit conversions (with the implicit and explicit keywords)

  • The literals true and false

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 the function is specified with the operator keyword followed by an operator symbol.

  • The operator function must be marked static.

  • 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 Note representing a musical note, and then overload the + operator:

 public struct Note { int value; ...

Get C# 3.0 Pocket Reference, 2nd Edition 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.