explicit keyword (C# Conversion Keywords)

The explicit keyword declares a user-defined type conversion operator that must be invoked with a cast. The conversion operator converts from a source type to a target type. The source type provides the conversion operator. Unlike implicit conversion, explicit conversion operators must be invoked by means of a cast.

Omitting the cast results in compile-time error CS0266.

Example: 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 fTemp)
{
fDegrees = fTemp;
}
// Must be defined inside a class called Celsius:
public static explicit operator Fahrenheit(Celsius c)
{
return new Fahrenheit((9.0f / 5.0f) * c.fDegrees + 32);
}
public float Degrees
{
get { return fDegrees; }
}
private float fDegrees;
}

class Fahrenheit
{
public Fahrenheit(float fTemp)
{
fDegrees = fTemp;
}
// Must be defined inside a class called Fahrenheit:
public static explicit operator Celsius(Fahrenheit fahr)
{
return new Celsius((5.0f / 9.0f) * (fahr.fDegrees - 32));
}
public float Degrees
{
get { return fDegrees; }
}
private float fDegrees;
}

class MainClass
{
static void Main()
{
Fahrenheit oFahrenheit = new Fahrenheit(100.0f);
Console.Write("{0} Fahrenheit", oFahrenheit.Degrees);
Celsius oCelsius = (Celsius)oFahrenheit; // Calls explicit conversion operator in Fahrenheit class

Console.Write(" = {0} Celsius", oCelsius.Degrees);
Fahrenheit oFahrenheit2 = (Fahrenheit)oCelsius; // Calls explicit conversion operator in Celsius class
Console.WriteLine(" = {0} Fahrenheit", oFahrenheit2.Degrees);
}
}

No comments:

Post a Comment