Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

casting

clr

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?

like image 578
pencilCake Avatar asked Mar 04 '12 17:03

pencilCake


1 Answers

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.

like image 110
SLaks Avatar answered Oct 10 '22 22:10

SLaks