O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, 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 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 3 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 (add two fractions, multiply, and so on) 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) ...

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