Conversion Operators
C#
converts int
to
long
implicitly, and allows you to convert
long
to int
explicitly. The
conversion from int
to long
is
implicit
because you know that any
int
will fit into the memory representation of a
long
. The reverse operation, from
long
to int
, must be
explicit
(using a cast) because it is
possible to lose information in the conversion:
int myInt = 5; long myLong; myLong = myInt; // implicit myInt = (int) myLong; // explicit
You must have the same functionality for your
fractions.
Given an int
, you can support an implicit
conversion to a fraction because any whole value is equal to that
value over 1 (e.g., 15==15/1
).
Given a fraction, you might want to provide an explicit conversion
back to an integer, understanding that some value might be lost.
Thus, you might convert 9/4
to the integer value
2
.
The keyword implicit
is used
when the conversion is guaranteed to succeed and no information will
be lost; otherwise explicit
is used.
Example 6-1 illustrates how you might implement
implicit and explicit conversions, and some of the operators of the
Fraction
class. (Although I’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 of the test statements, 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( ...
Get Programming C#, Second 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.