Creating Useful Operators

Operator overloading can make your code more intuitive and enable you to use instances of your classes as though they were built-in types. However, when you overload an operator for your class, the way you’re using it has to make sense. If you start to give your operators values that don’t naturally follow from their traditional meanings, you’ll just confuse anyone else who tries to use your class, possibly including yourself.

For example, although it might be tempting to overload the increment operator (++) on an employee class to invoke a method incrementing the employee’s pay level, this can create tremendous confusion. The increment operator normally means “increase this scalar value by one.” Giving it the new meaning of “increase this employee’s pay level” may be obvious when you implement the operator, but confusing to other programmers who have to maintain the code. It is best to use operator overloading sparingly, and only when its meaning is clear and consistent with how the built-in classes operate. You’ll find that there aren’t very many situations where it makes sense to overload the traditional arithmetic operators.

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.