Lesson 26

Overloading Operators

In Lesson 25 you learned how to overload a class's methods. C# also lets you overload operators 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.

Overloadable Operators

In C#, you can overload the unary, binary, and comparison operators listed in Table 26.1.

Table 26.1

Type Operators
Unary +, , !, ˜, ++, --
Binary +, , *, /, %, &, |, ^, ,
Comparison ==, !=, <, >, <=, >=

The comparison operators come in pairs. For example, if you overload the < operator, you must also overload the > operator.

The compound ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.