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?
Implicit conversions are evil, for several reasons. They make it hard to see what goes on in code. For instance, they might hide bad surprises like side effects or complex computations without any trace in the source code.
The Implicit Operator In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting. And such a kind of class can also be assigned to any convertible object or variable.
In C#, you can perform the following kinds of conversions: Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
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.
The reason it's not allowed is that it's pointless. The Explicit forces you to cast, the implicit allows you to forget about casting, but still allows you to cast. Implicit extends on the functionality of Explicit. So comment out your Explicit operator and smile :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With