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){

Get From Java to C#: A Developer's Guide 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.