The following example provides a Fahrenheit and a Celsius class, each of which provides an explicit conversion operator to the other class.
|
class Celsius
{
public Celsius(float temp)
{
degrees = temp;
}
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
}
public float Degrees
{
get { return degrees; }
}
private float degrees;
}
class Fahrenheit
{
public Fahrenheit(float temp)
{
degrees = temp;
}
// Must be defined inside a class called Farenheit:
public static explicit operator Celsius(Fahrenheit f)
{
return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
}
public float Degrees
{
get { return degrees; }
}
private float degrees;
}
class MainClass
{
static void Main()
{
Fahrenheit f = new Fahrenheit(100.0f);
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f;
Console.Write(" = {0} celsius", c.Degrees);
Fahrenheit f2 = (Fahrenheit)c;
Console.WriteLine(" = {0} fahrenheit", f2.Degrees);
}
}
/*
Output:
100 fahrenheit = 37.77778 celsius = 100 fahrenheit
*/
|
The following example defines a struct, Digit, that represents a single decimal digit. An operator is defined for conversions from byte to Digit, but because not all bytes can be converted to a Digit, the conversion is explicit.
|
struct Digit
{
byte value;
public Digit(byte value)
{
if (value > 9)
{
throw new ArgumentException();
}
this.value = value;
}
// Define explicit byte-to-Digit conversion operator:
public static explicit operator Digit(byte b)
{
Digit d = new Digit(b);
Console.WriteLine("conversion occurred");
return d;
}
}
class ExplicitTest
{
static void Main()
{
try
{
byte b = 3;
Digit d = (Digit)b; // explicit conversion
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
/*
Output:
conversion occurred
*/
|