Section 6.1. Using the operator Keyword


6.1. Using the operator Keyword

In C#, you implement operators by creating static methods whose return values represent the result of an operation and whose parameters are the operands. When you create an operator for a class you say you have "overloaded" that operator, much as you might overload any member method. Thus, to overload the addition operator (+), you would write:

public static Fraction operator+(Fraction lhs, Fraction rhs)

It is my convention to name the parameters lhs and rhs. The parameter name lhs stands for "lefthand side" and reminds me that the first parameter represents the lefthand side of the operation. Similarly, rhs stands for "righthand side."

The C# syntax for overloading an operator is to write the word operator followed by the operator to overload. The operator keyword is a method modifier. Thus, to overload the addition operator (+), write operator+.

When you write:

Fraction theSum = firstFraction + secondFraction;

the overloaded + operator is invoked, with the first Fraction passed as the first argument, and the second Fraction passed as the second argument. When the compiler sees the expression:

firstFraction + secondFraction

it translates that expression into:

Fraction.operator+(firstFraction, secondFraction)

The result is that a new Fraction is returned, which in this case is assigned to the Fraction object named theSum.

C++ programmers take note: it is not possible to create nonstatic operators, and thus binary operators must take two operands.




Programming C#(c) Building. NET Applications with C#
Programming C#: Building .NET Applications with C#
ISBN: 0596006993
EAN: 2147483647
Year: 2003
Pages: 180
Authors: Jesse Liberty

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