C # implement implicit user-defined type conversion (Keyword: Implicit operator)

Source: Internet
Author: User
/*
* Created by sharpdevelop.
* User: noo
* Date: 2009-9-1
* Time: 13:19
*
* The predefined Data Types of the system, such as int, float, double, and string, sometimes cannot meet our needs. In this case, we need our own data types, custom Data Type
* However, by default, custom data types cannot be converted from the predefined types in the system. In this case, custom data types do not work at all. Therefore, to use custom data types in the system
* You need to convert the user-defined data type to the data that can be recognized by the system and converted from the predefined data type for use by the system.
*
* Implicit user-defined type conversion: the keyword implicit. A custom type that can be implicitly converted to the float type is created below.
* In fact, the int type is a type that can be implicitly converted to float. Currently, the created type can be fully considered as the int type.
*/

Using system;
Class mytype // defines its own type, which is equivalent to the int type
{
Private int A, B;
Public mytype (int A, int B)
{
This. A =;
This. B = B;
}
Public Static Implicit operator float (mytype m) // implement implicit conversion to the float data type method. Note the modifier and keyword writing here.
{
Return m. A + M. B/10f; // by default, the real number on the right of the value assignment operator is treated as double. Therefore, use the suffix f or F to initialize floating point variables.
}
}
Class Test
{
Static void main ()
{
Mytype Mt = new mytype (12, 6); // equivalent to int Mt = 12
Float F = MT; // here is an implicit conversion, equivalent to float F = Mt
Console. writeline (f); // output 12.6
}
}

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.