O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Conversion Operators

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 the memory representation of 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

You want to be able 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. This idea is left, as they say, as an exercise for the reader, to keep this example simple.

You use the keyword implicit when the conversion is guaranteed to succeed and no information will be lost; otherwise, you use explicit. implicit and explicit are actually operators, often called cast or casting operators because their job is to cast from one type to another (int to Fraction or Fraction to int).

Example ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required