Search code examples
c#operator-overloadingimplicit-conversionexplicit-conversion

Why can't coexist implicit and explicit operator of the same type in C#?


Why can not coexist in the same class two operators (explicit and implicit) of the same type? Suppose I have the following:

public class Fahrenheit
{
    public float Degrees { get; set; }

    public Fahrenheit(float degrees) 
    {
        Degrees = degrees;
    }

    public static explicit operator Celsius(Fahrenheit f)
    {
        return new Celsius(ToCelsius(f.Degrees));
    }

    public static implicit operator Celsius(Fahrenheit f)
    {
        return new Celsius(ToCelsius(f.Degrees));
    }
}

public class Celsius {
    public float Degrees { get; set; }
    public Celsius(float degrees) 
    {
        Degrees = degrees;
    }

}

So I can give the client the possibility that use of either of two ways, for example:

Fahrenheit f = new Fahrenheit(20);
Celsius c1 = (Celsius)f;
Celsius c2 = f;

Is there any special reason why this is not allowed or is it just a convention to avoid a misuse of the programmer?


Solution

  • According to Overloading Implicit and Explicit Operators page:

    That's correct. Defining an implicit operator also allows for explicit conversion. Defining an explicit operator allows only for explicit conversion.

    Thus, if you define an explicit operator, you can do the following:

    Thing thing = (Thing)"value";

    If you define an implicit operator, you can still do the above, but you can also take advantage of implicit conversion:

    Thing thing = "value";

    So in short, explicit allows only explicit conversion, while implicit allows both explicit and implicit... hence the reason you can only define one.