It is a
design goal of C# that user-defined classes have all the
functionality of built-in types. For example, suppose you have
defined a type to represent fractions. Ensuring that this class has
all the functionality of the built-in types means that you must be
able to perform arithmetic on instances of your fractions (e.g., add
two fractions, multiply, etc.) and to convert fractions to and from
built-in types such as integer (int
). You could,
of course, implement methods for each of these operations and invoke
them by writing statements such as:
Fraction theSum = firstFraction.Add(secondFraction);
Although this will work, it is ugly and not how the built-in types are used. It would be much better to write:
Fraction theSum = firstFraction + secondFraction;
Statements like this are intuitive and consistent with how built-in
types, such as int
, are added.
In this chapter you will learn techniques for adding standard operators to your user-defined types. You will also learn how to add conversion operators so that your user-defined types can be implicitly and explicitly converted to other types.
In C#, operators are 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 (+
) you 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
.
18.118.20.231