Creating an Explicit Conversion Operator
Syntax
The syntax for creating an explicit conversion operator is similar to that of the implicit version. Only the implicit keyword is changed. The syntax is therefore:
public static explicit operator result-type(op-type operand)
Adding Single Conversion to the Vector Class
We will use the explicit version of the conversion operator syntax to allow the Vector to be cast as a single-precision floating point value representing the vector's length. The choice of explicit operator is due to the loss of accuracy of the number when the length is converted from a double to a float.
To add the new conversion operator, add the following code to the Vector class:
public static explicit operator float(Vector v)
{
return (float)v.Length;
}
The new conversion can be tested using the updated Main method below. Note the loss of accuracy that occurs when the vector's length is cast.
static void Main(string[] args)
{
Vector v = new Vector(5, 5);
float f = (float)v;
Console.WriteLine(f); // Outputs 7.071068
}
NB: The use of the (float) operator is required in this example as the conversion has been defined as explicit. Removing this cast operator causes a compiler error.
30 December 2007