We know that these two addition statements are equivalent and compile to the same IL code:
int x = 100;
x += 100;
x = x + 100;
However, when there is an explicit cast required I have noticed something strange:
byte b = 100;
b += 200; // Compiles (1)
b = b + 200; // Cannot implicitly convert int to byte (2)
b = (byte) (b + 200); // Compiles (3)
It is obvious why the second statement requires an explicit cast because the result of the addition is an integer. But the weird thing to me is the first statement. It compiles to the exact same IL as the third statement, so it looks like compiler adds a cast that is supposed to be explicit, for us. But it can't do it in the second statement.
It seems contradictory to me because I would expect the first statement to be equivalent to the second and never compile, so why does it compile?
Note: This doesn't compile when an explicit cast is required from long to int:
int x = 100;
long y = 200;
x += y;