O'Reilly logo

C# 3.0 Pocket Reference, 2nd Edition by Ben Albahari, Joseph Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required