Question

C# += operator overloading issues

I'm trying to overload operator += .. of course this's not possible by code but If I have not been fooled by docs once overloaded the + operator the += operator will be implicity overloaded.

public class Register {
    private byte data;

    public Register(byte value = 0x00) { data = value; }

    public Register(Register value)
    {
        data = value.data;
    }
    
    public static byte operator +(Register lvalue, byte rvalue)
    {
        return (byte)(lvalue.data + rvalue);
    }
    
    public static byte operator +(byte lvalue, Register rvalue)
    {
        return (byte)(lvalue + rvalue.data);
    }

    public static implicit operator byte(Register value) => value.data;
}

I tried with many other operator and the result is more or less the same.. the compiler complains (instead compile) about missing explicit cast.

The error is:

Compilation error (line 140, col 3): Cannot implicitly convert type 'byte' to 'Register'. An explicit conversion exists (are you missing a cast?)

Class fiddle

 3  78  3
1 Jan 1970

Solution

 6

Your + operator returns a byte, so += is equivalent to:

Register = Register + byte

But the byte cannot be implicitly casted back to a Register (only explicitly). Either make your explicit operator Register(byte value) implicit:

public static implicit operator Register(byte value) => new Register(value);

or make your + operator return Register:

public static Register operator +(Register lvalue, byte rvalue)
{
    return (Register)(byte)(lvalue.data + rvalue);
}
2024-07-23
ipodtouch0218