Operator Overloading Tips and Restrictions


The action of an overloaded operator as applied to the class for which it is defined need not bear any relationship to that operator’s default usage, as applied to C#’s built-in types. However, for the purposes of the structure and readability of your code, an overloaded operator should reflect, when possible, the spirit of the operator’s original use. For example, the + relative to ThreeD is conceptually similar to the + relative to integer types. There would be little benefit in defining the + operator relative to some class in such a way that it acts more the way you would expect the / operator to perform, for instance. The central concept is that while you can give an overloaded operator any meaning you like, for clarity it is best when its new meaning is related to its original meaning.

There are some restrictions to overloading operators. You cannot alter the precedence of any operator. You cannot alter the number of operands required by the operator, although your operator method could choose to ignore an operand. There are several operators that you cannot overload. Perhaps most significantly, you cannot overload any assignment operator, including the compound assignments, such as +=. Here are the other operators that cannot be overloaded. (This list includes several operators that are discussed later in this book.)

&&

||

[ ]

( )

new

is

sizeof

typeof

?

->

.

=

as

  

Although you cannot overload the cast operator ( ) explicitly, you can create conversion operators, as shown earlier, that perform this function.

It may seem like a serious restriction that operators such as += can’t be overloaded, but it isn’t. In general, if you have defined an operator, then if that operator is used in a compound assignment, your overloaded operator method is invoked. Thus, += automatically uses your version of operator+( ). For example, assuming the ThreeD class, if you use a sequence like this:

 ThreeD a = new ThreeD(1, 2, 3); ThreeD b = new ThreeD(10, 10, 10); b += a; // add a and b together

ThreeD’s operator+( ) is automatically invoked, and b will contain the coordinate 11, 12, 13.

One last point: Although you cannot overload the [ ] array indexing operator using an operator method, you can create indexers, which are described in the next chapter.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net