Conversion Operators
As you learned back in Chapter 3, C# will convert (for example) an int
to a long
implicitly but will only allow you to convert a long
to an int
explicitly. The conversion from int
to long
is implicit because you know that any int
will fit into a long
without losing any information. 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
It would certainly be useful to convert your Fraction
objects to intrinsic types (such as int
) and back. Given an int
, you can support an implicit conversion to a fraction because any whole value is equal to that value over 1 (15 == 15/1
).
Given a fraction, you might want to provide an explicit conversion back to an integer, understanding that some information might be lost. Thus, you might convert 9/4 to the integer value 2 (truncating to the nearest whole number).
Tip
A more sophisticated Fraction
class might not truncate, but rather round to the nearest whole number. Again, we’re trying to keep this example simple, but feel free to implement a more sophisticated method.
To implement the conversion operator, you still use the keyword operator
, but instead of the symbol you’re overriding, you use the type that you’re converting to. For example, to convert your Fraction
to an int
, you’d do this:
public static implicit operator Fraction( int theInt )
You use the keyword ...
Get Learning C# 3.0 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.