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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With