O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

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

23.1. The implicit and explicit keywords

In the above example, you can only perform a cast from Inch to Cm explicitly. That is, if you were to do this:

Cm cm1 = inch; // implicit cast

instead of this:

Cm cm1 = (Cm)inch; // explicit cast

You would get a compile-time error which reads: 'Cannot implicitly convert type Inch to Cm'.

It is possible to allow implicit casting by replacing the explicit keyword in the conversion method declaration by implicit. Instead of:

13:   public static explicit operator Cm (Inch toConvert){

replacing the explicit keyword by implicit will enable implicit casting of an Inch object to a Cm type:

13:   public static implicit operator Cm (Inch toConvert){

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