SoFunction
Updated on 2025-03-01

Introduction to user-defined data type conversion in c#

c# allows users to perform two defined data type conversions, explicit and implicit, which explicitly requires explicit tag conversion in code by writing the target data type in parentheses.

For predefined data types, some data may fail or lose when converting data types, and explicit conversion is required.

1 When converting the int value to short, short may not contain the converted value.

2 Convert signed data to unsigned data. If the signed variable contains a negative value, it will get incorrect results.

3 When converting floating point numbers to integer data types, the decimal part of the number will be lost.

At this time, explicit data types should be made in the code, so these may be taken into account when writing code.

C# allows you to define your own data types, which means that some tools need to support data conversion between your own data types. The method is to define the data type conversion as a member operator of the related class. The data type conversion must be declared implicit or explicit to illustrate how to use it.

Notice:If the source data value fails to convert the data, or an exception may be thrown, the data type conversion should be defined as explicit.

The syntax for defining data type conversion is similar to operator overloading.

For example: Implicit type conversion:

Copy the codeThe code is as follows:

public static implicit operator float(Current current)
{
}

Same as operator overloading, data type conversion must be declared as public and static.

Notice:

When the data type conversion is declared implicit, the compiler can call the data type conversion explicitly or implicitly.

When the data type conversion is declared explicit, the compiler can only explicitly call the type conversion.

Here is a small example:

Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;

namespace type conversion
{
struct Current
{
public uint Dollars;
public ushort Cents;

public Current(uint dollars, ushort cents)
{
= dollars;
= cents;
}

public override string ToString()
{
return ("{0}.{1,-2:00}",Dollars,Cents);
}

public static implicit operator float(Current value)
{
return +(/100.0f);
}

public static explicit operator Current(float f)
{
uint dollars = (uint)f;
ushort cents = (ushort)((f - dollars) * 100);
return new Current(dollars,cents);
}

}

class Program
{
static void Main(string[] args)
{
try
{
Current balance = new Current(50, 35);
(balance);
("balance using tostring(): "+());
float balance2 = balance;
("After converting to float,= " + balance2);
balance = (Current)balance2;
("After converting to Current,= " + balance);
float t = 45.63f;
Current c = (Current)t;
(());

checked
{
balance = (Current)(-50.5);
("Result is:" + ());
}
}
catch ( ex)
{
("Exception occurred:" + );
}
();
}
}
}


Two issues will be involved:

1 Convert from float to Current to get the wrong result 50.34, instead of 50.35.----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Answer: If the float value is converted to a uint value, the computer will truncate the excess number instead of rounding it. Data in computers is stored in binary, not in decimal, and the decimal part 0.35 cannot be stored in binary form. Because part of it is discarded, the actual data converted must be less than 0.35, that is, the value stored in binary form can be multiplied by 100 to obtain a number 34 less than 35. Sometimes this stage is very dangerous. When avoiding this wrong way, ensure that intelligent rounding operations are performed during the digital conversion process.

Microsoft wrote a class to accomplish the task. Contains a large number of static methods to perform various digital transformations, and we want to use Convert.ToUInt16(). Note that additional performance losses are generated when used, so they are only used when needed.

Note: Methods also perform their own overflow checks, so

Copy the codeThe code is as follows:

Convert.ToUInt16((f - dollars) * 100);

It can not be placed in checked.

2 No exception occurred while trying to convert out-of-range values. Mainly because: the location where the overflow occurs is not in the Main routine at all - this happens in the code of the conversion operator, and the change code is called in the Main() method, which is not marked as checked. The solution:

Copy the codeThe code is as follows:

 public static explicit operator Current(float f)
{
checked
{
uint dollars = (uint)f;
ushort cents = Convert.ToUInt16((f - dollars) * 100);
return new Current(dollars, cents);
}
}<SPAN style="FONT-FAMILY: Arial, Verdana, sans-serif">
</SPAN>