O'Reilly logo

Programming C# 3.0, 5th Edition by Donald Xie, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Operator Overloading

It is a design goal of C# that user-defined classes can have all the functionality of built-in types. For example, suppose you have defined a type to represent fractions. Ensuring that this class has all the functionality of the built-in types means that you must be able to perform arithmetic on instances of your fractions (e.g., add two fractions, multiply, etc.) and convert fractions to and from built-in types such as integer (int). You could, of course, implement methods for each operation and invoke them by writing statements such as:

Fraction theSum = firstFraction.Add(secondFraction);

Although this will work, it is ugly, and is not how the built-in types are used. It would be much better to write:

Fraction theSum = firstFraction + secondFraction;

Statements like this are intuitive and consistent with how built-in types, such as int, are added.

In this chapter, you will learn techniques for adding standard operators to your user-defined types. You will also learn how to add conversion operators so that your user-defined types can be implicitly and explicitly converted to other types.

Using the operator Keyword

In C#, you implement operators by creating static methods whose return values represent the result of an operation and whose parameters are the operands. When you create an operator for a class you say that you have “overloaded” that operator, much as you might overload any member method. Thus, to overload the addition operator (+), you would ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required