C User defined type conversion details
- 2020-06-03 08:07:00
- OfStack
C# User-defined conversions
The & # 8226; Use for custom classes and structures to perform implicit and explicit conversions. For example: convert 1 custom class type to integer, floating point, etc., and vice versa.
C# provides both implicit and explicit transformations
The & # 8226; Implicit conversion: The compiler performs the conversion automatically
The & # 8226; Explicit conversion: The compiler performs the conversion only when the explicit conversion operator is used
The syntax for declaring implicit transformations is as follows. Note: All user-defined transformations must use the public and static modifiers
public static implicit operator TargetType(SourceType Identifier)
{
...
return ObjectOfTargetType;
}
TargetType: Target type
Parameter Identitfier: source data
For example, the following code causes an int literal to be implicitly converted to an LimitedInt object, which in turn can be implicitly converted to an int
class LimitedInt
{
const int MaxValue = 100;
const int MinValue = 0;
private int _theValue = 0;
// attribute
public int TheValue
{
get { return _theValue; }
set
{
if (value < MinValue)
{
_theValue = 0;
}
else
{
_theValue = value > MaxValue ? MaxValue : value;
}
}
}
// Implicit conversion : will LimitedInt Object to integer
public static implicit operator int(LimitedInt li)
{
return li.TheValue;
}
// Implicit conversion : Converts an integer to LimitedInt object
public static implicit operator LimitedInt(int x)
{
LimitedInt li = new LimitedInt();
li.TheValue = x;
return li;
}
}
class Program
{
static void Main(string[] args)
{
LimitedInt li = 500; // will 500 convert LimitedInt
int value = li; // will LimitedInt convert int
Console.WriteLine("li:{0},value:{1}", li.TheValue, value);
Console.ReadKey();
}
Code output :li:100,value:100
Displays the transform and cast operators
All of this is implicit conversion. If you change the operator implcit to explicit, you will have to show the use of the conversion operator when performing the conversion
The code snippet is as follows:
// According to conversion : will LimitedInt Object to integer
public static explicit operator int(LimitedInt li)
{
return li.TheValue;
}
// According to conversion : Converts an integer to LimitedInt object
public static explicit operator LimitedInt(int x)
{
LimitedInt li = new LimitedInt();
li.TheValue = x;
return li;
}
static void Main(string[] args)
{
LimitedInt li = (LimitedInt)500; // will 500 Cast to LimitedInt
int value = (int)li; // will LimitedInt Cast to int
Console.WriteLine("li:{0},value:{1}", li.TheValue, value);
Console.ReadKey();
}