Information Technology Reference
In-Depth Information
User-Defined Type Conversions
User-defined conversions will be discussed in greater detail in Chapter 18, but I will mention
them here as well because they are operators.
You can define both implicit and explicit conversions for your own classes and structs.
This allows you to convert an object of your user-defined type to some other type, and
vice versa.
C# provides implicit and explicit conversions.
-With an
implicit conversion
, the compiler will automatically make the conversion, if
necessary, when it is resolving what types to use in a particular context.
-With an
explicit conversion
, the compiler will only make the conversion when an
explicit cast operator is used.
The syntax for declaring an implicit conversion is the following. The syntax for the explicit
conversion is the same, except that
explicit
is substituted for
implicit
.
The modifiers
public
and
static
are required for all user-defined conversions.
Required
Target
Source
↓
↓
↓
public static implicit operator
TargetType
(
SourceType Identifier
)
{
...
return
ObjectOfTargetType
;
}
The following code shows an example of declarations for conversion operators that will
convert an object of type
LimitedInt
to type
int
, and vice versa.
class LimitedInt
Target
Source
{
↓
↓
public static implicit operator int (LimitedInt li)
{
return li.TheValue;
}
Target
Source
↓
↓
public static implicit operator LimitedInt (int x)
{
LimitedInt li = new LimitedInt();
li.TheValue = x;
return li;
}
private int _TheValue = 0;
public int TheValue{ ... }
}