[Previous] [Contents] [Next]

Overloadable Operators

Only the following unary and binary operators can be overloaded.

Unary operands: +, -, !, ~, ++, --, true, false -

Binary operands: +, -, *, /, %, &, |, ^, <<, >>, ==, !=, >, <, >=, <= -

The comma is used here to separate the different overloadable operators. The comma operator, which is used in the for statement and in method calls, cannot be overloaded.

Restrictions on Operator Overloading

It is not possible to overload the = assignment operator. However, when you overload a binary operator, its compound assignment equivalent is implicitly overloaded. For example, if you overload the + operator, the += operator is implicitly overloaded in that the user-defined operator+ method will be called.

The [] operators can't be overloaded. However, as you saw in Chapter 7, user-defined object indexing is supported through indexers.

The parentheses used to perform a cast are also not overloadable. Instead, you should use conversion operators, which are also referred to as user-defined conversions, the subject of the second half of this chapter.

Operators that are currently not defined in the C# language cannot be overloaded. You can't, for example, define ** as a means of defining exponentiation because C# does not define a ** operator. Also, an operator's syntax can't be modified. You can't change the binary * operator to take three arguments when, by definition, its syntax calls for two operands. Finally, an operator's precedence can't be altered. The rules of precedence are static-see Chapter 10, "Expressions and Operators," for more on these rules.

[Previous] [Contents] [Next]