Using the operator Keyword

In C#, operators are static methods. The return value of an operator represents the result of an operation. The operator’s parameters are the operands.

You can define an addition operator for a Fraction class as you would any other class method, but with a bit of a difference. Instead of a method name, you use the C# syntax of combining the operator keyword with the plus sign (+) operator, combined with the keyword static. For example, the overloaded addition operator (the operator+ method) takes two Fraction objects (the fractions you want to add) as parameters and returns a reference to another Fraction object representing the sum of the two parameters. Here is its signature:

public static Fraction operator+(Fraction lhs, Fraction rhs)

And here’s what you can do with it. Assume, for instance, that you’ve defined two fractions representing the portion of a pie you’ve eaten for breakfast and lunch, respectively. (You love pie.)

Fraction pieIAteForBreakfast = new Fraction(1,2); // 1/2 of a pie
Fraction pieIAteForLunch = new Fraction(1,3);     // 1/3 of a pie

The overloaded operator+ allows you to figure out how much pie you’ve eaten in total. (And there’s still 1/6 of the pie leftover for dinner!) You would write:

Fraction totalPigOut = pieIAteForBreakfast + pieIAteForLunch;

The compiler takes the first operand (pieIAteForBreakfast) and passes it to operator+ as the parameter lhs; it passes the second operand (pieIAteForLunch) as rhs. These two Fractions are then ...

Get Learning C# 3.0 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.