C Sharp

Design Guidelines

You've seen what operator overloading is and how to use it in C#, so let's examine an often-ignored aspect of this useful feature: design guidelines. What you want to stay away from is the natural tendency to want to use a new feature for the sake of using it. This phenomenon is sometimes referred to as "a solution in search of a problem." But it's always a good design approach to remember the adage, "Code is read more than it is written." Keep the class's client in mind when determining if and when to overload an operator or set of operators. Here's a rule of thumb: you should overload an operator only if it makes the class's interface more intuitive to use. For example, it makes perfect sense to be able to add invoices together.

In addition, don't forget that you have to think as a client of your class would. Let's say you're writing an Invoice class and you want the client to be able to discount the invoice. You and I might know that a credit line item will be added to the invoice, but the point of encapsulation is that your clients don't have to know the exact implementation details of the class. Therefore, overloading the * operator-as shown here-might be a good idea because it would serve to make the Invoice class's interface natural and intuitive: -

    invoice *= .95; // 5% discount.

User-Defined Conversions

Earlier I mentioned that the parentheses used for casting cannot be overloaded and that user-defined conversionsmust be used instead. In short, user-defined conversions enable you to declare conversions on structures or classes such that the struct or class can be converted to other structures, classes, or basic C# types. Why and when would you want to do that? Let's say you needed to use the standard Celsius and Fahrenheit temperature scales in your application such that you could easily convert between the two. By creating user-defined conversions, you could use the following syntax: -

Fahrenheit f = 98.6F;
Celsius c = (Celsius)f; // User-defined conversion.

This doesn't provide any functional benefits over the following syntax, but it is more intuitive to write and easier to read.

Fahrenheit f = 98.6F;
Celsius c = f.ConvertToCelsius();