Home C# Operator Overloading and User-Defined Conversions

C# - Operator Overloading and User-Defined Conversions


In tutorial 7, "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.

[Next]