The implicit keyword is used to declare an implicit user-defined type conversion operator. If you can ensure that the conversion process does not cause data loss, you can use this keyword to perform implicit conversion between user-defined types and other types.
Example
C #
Class Digit
{
Public Digit (double d) {val = d ;}
Public double val;
//... Other members
// User-defined conversion from Digit to double
Public static implicit operator double (Digit d)
{
Return d. val;
}
// User-defined conversion from double to Digit
Public static implicit operator Digit (double d)
{
Return new Digit (d );
}
}
Class Program
{
Static void Main (string [] args)
{
Digit dig = new Digit (7 );
// This call invokes the implicit "double" operator
Double num = dig;
// This call invokes the implicit "Digit" operator
Digit dig2 = 12;
Console. WriteLine ("num = {0} dig2 = {1}", num, dig2.val );
Console. ReadLine ();
}
}
}
Implicit conversion can improve the readability of source code by eliminating unnecessary type conversion. However, because implicit conversion does not require the programmer to explicitly convert one type to another type, you must be careful when using implicit conversion to avoid unexpected results. Generally, implicit conversion operators should never cause exceptions and never lose information, so that they can be safely used without the programmer's knowledge. If the conversion operator cannot meet those conditions, mark it as explicit. For more information, see use conversion operators.