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/4The 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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access