Information Technology Reference
In-Depth Information
Explicit Conversion and the Cast Operator
The preceding example code showed the implicit conversion of the
int
to a
LimitedInt
type
and the implicit conversion of a
LimitedInt
type to an
int
. If, however, you had declared the
two conversion operators as
explicit
, you would have had to explicitly use cast operators
when making the conversions.
A
cast operator
consists of the name of the type to which you want to convert the expres-
sion, inside a set of parentheses. For example, the following casts the value
5
to a
LimitedInt
object.
Cast operator
↓
LimitedInt li = (LimitedInt) 5;
For example, here is the relevant portion of the code, with the changes marked:
↓
public static explicit operator int(LimitedInt li)
{
return li.TheValue;
}
↓
public static explicit operator LimitedInt(int x)
{
LimitedInt li = new LimitedInt();
li.TheValue = x;
return li;
}
static void Main()
{
↓
LimitedInt li = (LimitedInt) 5;
int Five = (
int
) li;
↑
Console.WriteLine(" li: {0}, Five: {1}", li.TheValue, Five);
}
In both versions of the code, the output is the following:
li: 5, Five: 5