An
implicit keyword is used to declare an implicit user-defined
type conversion operator. It is used to enable implicit (automatic)
conversions between a user-defined type and another type, if the
conversion is guaranteed not to cause a loss of data.
Implicit
conversions can improve source code readability by eliminating
unnecessary casts. Care must be taken to prevent unexpected results
because implicit conversions do not require programmers to explicitly
cast from one type to the other. In general, implicit conversion
operators should never throw exceptions and never lose information so
that they can be used safely without the programmer's awareness. If a
conversion operator cannot meet those criteria, it should be marked
explicit.
Example:
class
Digit
{
public
Digit(double
dValue) { dVal = dValue; }
public
double
dVal;
//
User-defined conversion from Digit to double
public
static
implicit
operator
double(Digit
oDigit)
{
return
oDigit.dVal;
}
//
User-defined conversion from double to Digit
public
static
implicit
operator
Digit(double
dDoubleVal)
{
return
new
Digit(dDoubleVal);
}
}
class
Program
{
static
void
Main(string[]
args)
{
Digit
oDigit = new
Digit(7);
double
dNum = oDigit; //This
call invokes the implicit "double" operator
Digit
oDigit2 = 12; //This
call invokes the implicit "Digit" operator
Console.WriteLine("dNum
= {0} oDigit2 = {1}",
dNum, oDigit2.dVal);
Console.ReadLine();
}
}
No comments:
Post a Comment