Designing the Fraction Class

For example, suppose you define a type to represent fractional numbers; you might reasonably name it Fraction. 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

It’s reasonable to create this class so that the first parameter will represent the numerator and the second parameter will represent the denominator. In general, when you create your classes, you should stick to an obvious and intuitive interpretation whenever you can.

If you want your Fraction class to have all the functionality of the built-in types, you’ll need to be able to perform arithmetic on instances of your fractions (add two fractions, multiply them, and so on). You should also be able 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, which you would invoke like this:

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

This works just fine, but it’s not very obvious. It’s hard to read, and it’s not how the user would automatically expect addition to work. It also doesn’t look like addition of the built-in types, such as int. 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.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset