Tip:
Highlight text to annotate it
X
In this section we’ll look at how to define custom type conversions for an object. As
we can see we here have a class called MyNum with a single integer field and a constructor.
What we want to do in this example is to allow an integer to be implicitly converted to an
object of this class.
For this to work we just need to add an implicit conversion method to the class. This method’s
signature looks similar to the one used for unary operator overloading. It must be declared
as public static and it includes the operator keyword. However, instead of an operator symbol
the return type is specified, which is the target type for the conversion, and the parameter
is the variable that needs to be converted. The implicit keyword is also included, which
specifies that the method is used to perform implicit conversions.
With this method added an integer can now be implicitly converted to a MyNum object.
We may also add another conversion method that handles conversions in the opposite direction,
from a MyNum object to an integer.
If we want to prevent potentially unintended object type conversions by the compiler we
can declare the conversion method as explicit instead of implicit. This means that the programmer
have to specify an explicit cast in order to invoke the type conversion method. This
should especially be used if the result of the conversion leads to loss of information
or if the conversion method can throw exceptions.