Information Technology Reference
In-Depth Information
User-Defined Conversions
Besides the standard conversions, you can also define both implicit and explicit conversions
for your own classes and structs.
The syntax for user-defined conversions is shown following.
The syntax is the same for both implicit and explicit conversion declarations, except for
the keywords
implicit
or
explicit
.
The mod iers
public
and
static
are required.
Required
Target
Source
↓
↓
↓
public static implicit operator
TargetType
(
SourceType Identifier
)
{
↑
Implicit or explicit
...
return
ObjectOfTargetType
;
}
For example, the following shows an example of the syntax of a conversion method that
converts an object of type
Person
to an
int
.
public static implicit operator int(Person p)
{
return p.Age;
}
Constraints on User-Defined Conversions
There are some important constraints on user-defined conversions. The most important are
the following:
You can only define user-defined conversions for classes and structs.
You cannot redefine standard implicit or explicit conversions.
The following is true for source type
S
and target type
T
:
-
S
and
T
must be different types.
-
S
and
T
cannot be related by inheritance. That is,
S
cannot be derived from
T
, and
T
cannot be derived from
S
.
Neither
S
nor
T
can be an interface type or the type
object
.
-
The conversion operator must be a member of either
S
or
T
.
-
You cannot declare two conversions, one
implicit
, and the other
explicit
, with the
same source and target types.