Implicit (C # reference)

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.