
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 you’re 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