Alex Rivera | Logout

Does += operator ensures an EXPLICIT conversion or implicit CASTING in C#?

Asked 2012-03-04T17:25:52.940
9

The example below compiles:

public static void Main()
{
    Byte b = 255;
    b += 100;

}

but this one below fails

   public static void Main()
    {
        Byte b = 255;
        b = b + 100;
    }

with

Error 1 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

Does this mean that for C# += operator provides EXPLICIT conversion?

Edit
Report

1 Answer

11

Eric Lippert answered your question at great length.

Another interesting aspect of the predefined compound operators is that if necessary, a cast – an allegedly “explicit” conversion – is inserted implicitly on your behalf. If you say

short s = 123;
s += 10;

then that is not analyzed as s = s + 10 because short plus int is int, so the assignment is bad. This is actually analyzed as

s = (short)(s + 10);

so that if the result overflows a short, it is automatically cut back down to size for you.

See also part two.

answered 2012-03-04T17:28:08.937

Your Answer