Beef icon indicating copy to clipboard operation
Beef copied to clipboard

Implicit operator order within enum affects casting behavior

Open Grimelios opened this issue 10 months ago • 0 comments

public enum MyEnum
{
    public static implicit operator uint(Self self) => self;
    public static implicit operator int(Self);

    case A;
    case B;
    case C;
}

static
{
    public static void Main()
    {
        MyEnum e = ?;
        int i = e; // Works!
        uint8 u = (uint8)e; // Also works!
    }
}

I discovered this issue while experimenting with https://github.com/beefytech/Beef/issues/2150. The code above is identical to that issue except for two changes:

  1. The explicit cast uses uint8, not uint.
  2. There's a new public static implicit operator uint(Self self) => self; in MyEnum.

This code compiles successfully. However, swapping the order of the two implicit operators (i.e. int first, then uint) reintroduces the same issue as https://github.com/beefytech/Beef/issues/2150 ("Unable to implicitly cast int8 to uint8"). This indicates that declaration affects how operators are resolved. Whether this behavior is "correct" may be up for debate, but I'd argue it's unintuitive.

Grimelios avatar Feb 18 '25 20:02 Grimelios