Putting Operators to Work
Example 6-1 illustrates how you might implement implicit and explicit conversions, and some of the operators of the Fraction
class. (Although we've used Console.WriteLine( )
to print messages illustrating which method we're entering, the better way to pursue this kind of trace is with the debugger. You can place a breakpoint on each test statement, and then step into the code, watching the invocation of the constructors as they occur.) When you compile this example, it will generate some warnings because GetHashCode( )
is not implemented (see Chapter 9).
Example 6-1. Defining conversions and operators for the Fraction class
using System;
namespace Conversions
{
public class Fraction
{
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator)
{
Console.WriteLine("In Fraction Constructor(int, int)");
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction(int wholeNumber)
{
Console.WriteLine("In Fraction Constructor(int)");
numerator = wholeNumber;
denominator = 1;
}public static implicit operator Fraction(int theInt)
{
Console.WriteLine("In implicit conversion to Fraction");
return new Fraction(theInt);
}
public static explicit operator int(Fraction theFraction)
{
Console.WriteLine("In explicit conversion to int");
return theFraction.numerator / theFraction.denominator;
} public static bool operator ==(Fraction lhs, Fraction rhs) { Console.WriteLine("In operator =="); if (lhs.denominator == rhs.denominator ...
Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.