简体   繁体   中英

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

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM