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();