-
I added an explicit int conversion and it silently affected the explicit float conversion in a different project in the solution than the one I was working in. This resulted in fractions being lost. using System;
var number = new AWrapperType(123.456);
Console.WriteLine((float)number); // Prints "Oops" and "123"
public readonly struct AWrapperType
{
private readonly double value;
public AWrapperType(double value) => this.value = value;
public static implicit operator double(AWrapperType value)
{
return value.value;
}
public static explicit operator int(AWrapperType value)
{
Console.WriteLine("Oops");
return (int)value.value;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I believe this happens because of these parts of the section Processing of user-defined explicit conversions in the spec (emphasis mine):
In more concrete language, if you're doing an explicit cast, both implicit and explicit operators are considered, equally. What makes the difference here is the next step, where subsequent standard implicit conversions are considered (that's what "encompassed by" refers to), in both directions, but ones in the "correct" direction are preferred. Since there are standard implicit conversions from |
Beta Was this translation helpful? Give feedback.
I believe this happens because of these parts of the section Processing of user-defined explicit conversions in the spec (emphasis mine):