Chapter 12. Operator Overloading

Back in Chapters Chapter 3 and Chapter 4, you learned about the C# built-in types, such as integer (int) and Boolean (bool), and the various operators that let you work with those types, from the simple mathematical operators (such as + and %) to the comparison operators (== and <=) to the logical operators (&& and ||). Using most of these operators with the basic types is simple and intuitive. If you try to use those operators with classes you’ve created in the past few chapters, though, you’ll get an error. Back in Chapter 8, you saw how to overload the methods of your class, giving them additional functions, depending on the parameters. C# lets you extend that overloading ability to operators—arithmetic ones, comparison ones, and even the operator for casting one type to another—which is what we’ll show you in this chapter. Although being able to overload the arithmetic operators is great, it’s the equality operators that are really useful to overload, as you’ll see.

Get Learning C# 3.0 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.