- Define conversion operators to simplify narrowing and widening conversions between numberic types.
- Override ToString to provide conversion to strings, and override Parse to provide conversion from strings.
- Implement System.IConvertable to enable conversion through System.Convert. Use this technique to enable culture-specific conversions.
- Implement a TypeConverter class to enable design-time conversion for use in the Visual Studio Properties window.
Narrowing Conversion
If the range of precision of the source type exceeds that of the destination type, the operation is called a narrowing conversion, which will usually require an explicit conversion.
Widening Conversion
If the destination type can accomodate all possible values from the source type, that is known as a widening conversion and doesn't require an explicit cast.
Defining conversion operators allows you to directly assign from a value type to your custom type. Use the Widening/implicit keyword for conversions that don't loose precision; use the Narrowing/explicit keyword for conversions that could loose precision.
struct TypeA
{
public int Value;
// Allows implicit conversion from an integer.
public static implicit operator TypeA(int arg)
{
TypeA res = new TypeA();
res.Value = arg;
return res;
}
// Allows explicit conversion to an integer.
public static explicit operator int(TypeA arg)
{
return arg.Value;
}
// Provides string conversion (avoids boxing).
public override string ToString()
{
return this.Value.ToString();
}
}
public static void Main()
{
TypeA a;
int i;
// Widening conversion is OK implicit.
a = 42;
// Narrowing conversion must be explicit.
i = (int)a;
// ..
No comments:
Post a Comment