C# Tutorials - Operator Overloading and User-Defined Conversions
In tutorial "Properties, Arrays, and Indexers," you learned how to use the  operator with a class to programmatically index an object as if it were an array. In this tutorial, we'll look at two closely related features of C# that provide the ability to create structure and class interfaces that are easier and more intuitive to use: operator overloading and user-defined conversions. I'll start with a general overview of operator overloading in terms of the benefits it provides you and then look at the actual syntax for redefining the default behaviors of operators as well as a realistic example application in which I overload the + operator to aggregate multiple Invoice objects. After that, you'll see a listing of which binary and unary operators are overloadable as well as some of the restrictions involved. The operator overloading discussion will end with some design guidelines to take into account when deciding whether to overload operators in your classes. Once we've finished with operator overloading, you'll learn about a new concept, user-defined conversions. Once again, I'll start with broad strokes, explaining the basics of this feature, and then I'll dive into a class that illustrates how you can use conversions to enable the casting of a struct or class to a different struct, class, or basic C# type.
Operator overloading allows existing C# operators to be redefined for use with user-defined types. Operator overloading has been called "syntactic sugar," owing to the fact that the overloaded operator is simply another means of calling a method. It's also been said that the feature doesn't fundamentally add anything to the language. Although this is technically true, operator overloading does aid in one of the most important aspects of object-oriented programming: abstraction.
Suppose that you want to aggregate a collection of invoices for a particular customer. Using operator overloading, you can write code similar to the following in which the += operator is overloaded: -
Invoice summaryInvoice = new Invoice();
foreach (Invoice invoice in customer.GetInvoices())
summaryInvoice += invoice;
The benefits of such code include its very natural syntax and the fact that the client is abstracted from having to understand the implementation details of how the invoices are being aggregated. Simply put, operator overloading aids in creating software that is less expensive to write and maintain.
Table of content (tutorial index)