Overloading Operators
In Lesson 25 you learned how to overload a class’s methods. C# also lets you overload opera-
tors such as + and * to give them new meanings when working with the structures and classes
that you create. For example, you could overload the + operator so the program would know
how to add a
Student object and a Course object. Sometimes that allows you to use a more
natural syntax when youre working with objects.
In this lesson, you learn how to overload operators so you can use them to manipulate objects.
Before you jump into operator overloading, be warned that just because you
can overload an operator doesn’t mean you should. You should only overload
operators in intuitive ways.
For example, it makes sense to overload the + operator so you can add two
ComplexNumber objects. It might also make sense to overload + so you can add
an item to a purchase order.
It probably doesn’t make sense to define + between two Employee objects to
return a list of projects that included both employees. You could do that but you
probably shouldn’t because it would be confusing.
OVERLOADABLE OPERATORS
In C#, you can overload unary, binary, and logical operators. Table 26-1 summarizes the
operators that you can overload.
26
596906c26.indd 311 4/7/10 12:34:02 PM
312
LESSON 26 OverlOading OperatOrs
TABLE 261
TYPE OPERATORS
Unary +, -, !, ~, ++, --
Binary +, –, *, /, %, &, |, ^, <<, >>
Comparison ==, !=, <, >, <=, >=
The comparison operators come in pairs. For example, if you overload the < operator then you must
also overload the > operator.
The compound assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, and >>=) are automatically
overloaded when you overload the corresponding binary operator. For example, if you overload *, then
C# automatically overloads *=.
The syntax for overloading operators is easiest to understand by looking at examples. The following
sections explain how to overload the different types of operators.
UNARY OPERATORS
The following code shows how you can overload the unary - operator for the ComplexNumber class:
public static ComplexNumber operator -(ComplexNumber me)
{
return new ComplexNumber(-me.Real, -me.Imaginary);
}
The method begins with public static followed by the operator’s return type. In this case the opera-
tor returns a
ComplexNumber because the negation of a complex number is another complex number.
Next comes the keyword
operator and the operator’s symbol, in this case -.
The parameter list tells on which class the operator should be defined. Because this code is defining
an operator for the
ComplexNumber class, that’s the parameters data type.
I often name this parameter
me to help me remember that this is the object to which the operator is
being applied.
Note that the overload must be declared inside the class used by the parameter. In this case, because
the parameter is a
ComplexNumber, this code must be in the ComplexNumber class.
The code inside this method simply negates the
ComplexNumbers real and imaginary parts and
returns a new
ComplexNumber.
The following code shows how a program might use this operator:
ComplexNumber a = new ComplexNumber(1, 2); // 1 + 2i
ComplexNumber minusA = -a; // -1 - 2i
596906c26.indd 312 4/7/10 12:34:02 PM
Binary Operators
313
BINARY OPERATORS
Overloading binary operators is similar to overloading unary operators except the operator takes a
second parameter. The first parameter is still the object to which the operator is being applied.
For example, the following code overloads the binary - operator to add two
ComplexNumbers:
public static ComplexNumber operator -(ComplexNumber me, ComplexNumber other)
{
return new ComplexNumber(me.Real - other.Real,
me.Imaginary - other.Imaginary);
}
The first parameter gives the object on the left of the – sign and the second parameter gives the
object on the right. To help keep them straight, I often name the parameters
me and other.
Note that the overload must be declared inside a class or structure used by one of the parameters. In
this case, because both parameters are
ComplexNumbers, this code must be in the ComplexNumber class.
While this example subtracts two
ComplexNumbers, the parameters do not need to have the same
data types. The following code defines the binary – operator for subtracting a
double from a
ComplexNumber:
public static ComplexNumber operator -(ComplexNumber me, double x)
{
return new ComplexNumber(me.Real - x, me.Imaginary);
}
Note that this is not the same as subtracting a ComplexNumber from a double. If you want to handle
that situation as well, you need the following separate overload:
public static ComplexNumber operator -(double me, ComplexNumber other)
{
return new ComplexNumber(me - other.Real, other.Imaginary);
}
With these overloads, a program could execute the following code:
ComplexNumber a = new ComplexNumber(2, 3);
ComplexNumber b = new ComplexNumber(4, 5);
ComplexNumber c = a - b; // ComplexNumber - ComplexNumber
ComplexNumber d = a - 10; // ComplexNumber - double
ComplexNumber e = 10 - a; // double - ComplexNumber
The shift operators << and >> are a little different from the other binary operators
because the second parameter must always be an integer.
596906c26.indd 313 4/7/10 12:34:03 PM
314
LESSON 26 OverlOading OperatOrs
COMPARISON OPERATORS
The comparison operators are simply binary operators that return a Boolean result. The only oddity
to these is that they come in pairs. For example, if you define ==, then you must also define !=. The
pairs are == and !=, < and >, and <= and >=.
The following code shows how you could overload the < and > operators for the
ComplexNumber class:
public static bool operator <(ComplexNumber me, ComplexNumber other)
{
return (me.Magnitude() < other.Magnitude());
}
public static bool operator >(ComplexNumber me, ComplexNumber other)
{
return (me.Magnitude() > other.Magnitude());
}
The Object class provides Equals and GetHashCode methods that are tied
closely to an object’s notion of equality because
Equals should return true if
two objects are equal and
GetHashCode should return the same value for two
objects that are considered equal. To avoid confusion, you should not overload
== and != unless you also override
Equals and GetHashCode. In fact, Visual
Studio flags an error if you overload == or != but not these two methods.
TRY IT
In this Try It, you extend the ComplexNumber class you built in Lesson 25, Exercise 1. That ver-
sion of the class included methods such as
AddTo and SubtractFrom to perform simple operations.
Now you’ll replace those cumbersome methods with overloaded +, -, *, and unary - operators.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson26 folder of the download.
Lesson Requirements
Copy the ComplexNumber program you built for Lesson 25, Exercise 1 (or download
Lesson 25’s version from the book’s web site). Remove the ComplexNumber class’s AddTo,
MultiplyBy, and SubtractFrom methods.
596906c26.indd 314 4/7/10 12:34:04 PM
Try It
315
Give the class new overloaded operators to handle these cases:
ComplexNumber + ComplexNumber
ComplexNumber + double
double + ComplexNumber
ComplexNumber * ComplexNumber
ComplexNumber * double
double * ComplexNumber
-ComplexNumber
ComplexNumber - ComplexNumber
ComplexNumber - double
double - ComplexNumber
Revise the main form’s code to use the new operators.
Hints
You can use operators to define other operators. For example, if you define the unary - oper-
ator, then the following two operations have the same result:
ComplexNumber - ComplexNumber
ComplexNumber + -ComplexNumber
Step-by-Step
Copy the ComplexNumber program you built for Lesson 25, Exercise 1 (or download
Lesson 25’s version from the book’s web site). Remove the ComplexNumber class’s AddTo,
MultiplyBy, and SubtractFrom methods.
1. This is reasonably straightforward.
Give the class new overloaded operators to handle these cases:
ComplexNumber + ComplexNumber
ComplexNumber + double
double + ComplexNumber
ComplexNumber * ComplexNumber
ComplexNumber * double
double * ComplexNumber
-ComplexNumber
ComplexNumber - ComplexNumber
596906c26.indd 315 4/7/10 12:34:04 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.199.14