23.1 The implicit and explicit keywords


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


From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net