DekGenius.com
Team LiB   Previous Section   Next Section

Chapter 12. Operator Overloading

One of the goals of C# is to allow you to create new classes that have all the functionality of built-in types such as integer (int) and Boolean (bool). (See Chapter 5 for a discussion of these intrinsic types.) For example, suppose you define a type (Fraction) to represent fractional numbers. The following constructors establish two Fraction objects, the first representing 1/2 and the second representing 3/4:

Fraction firstFraction = new Fraction(1,2); // create 1/2 
Fraction secondFraction = new Fraction(3,4); // create 3/4

The assumption here, of course, is that the first parameter will represent the numerator, and the second parameter will represent the denominator.

Ensuring that the Fraction 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 to convert fractions to and from built-in types such as int.

Hypothetically, you could implement methods for each of these operations. For example, for your Fraction type you might create an Add( ) method and invoke it by writing a statement such as:

// add 1/2 and 3/4 
Fraction theSum = firstFraction.Add(secondFraction);

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

// add 1/2 and 3/4 using + operator
Fraction theSum = firstFraction + secondFraction;

Statements that use operators (in this case the plus sign) are intuitive and easy to use. Equally important, this use of operators is consistent with how built-in types are added, multiplied, and so forth.

In this chapter, you will learn techniques for adding standard operators to be used with your user-defined types. When you create an operator for a class, you say you have "overloaded" that operator, much as you might overload a member method (discussed in Chapter 9). The C# syntax for overloading an operator is to write the keyword operator followed by the operator to overload. The next section demonstrates how you might do this for the Fraction class.

The chapter also discusses the special case of overloading the equals operator, which is used to test whether two objects are equal. Overriding this operator also requires you to override the class's Equals( ) method.

Later in the chapter, you will learn how to add conversion operators to your user-defined types so that they can be implicitly and explicitly converted to other types.

    Team LiB   Previous Section   Next Section