This line:
a += b;
Is equivalent to this line:
a = (byte) (a + b);
... except that a
is only evaluated once. The result of a + b
is of type int
(with a value of 300 in this case), and the cast to byte
truncates that to 8 bits (the size of the byte
type), leaving a result of 44.
From section 12.18.3 of the ECMA C# 5 standard:
An operation of the form x op= y
is processed by applying binary operator overload resolution (§12.4.5) as if the operation was written x op y
. Then,
- If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as
x = x op y
, except that x
is evaluated only once.
- Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of
x
, and if y
is implicitly convertible to the type of x
or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y)
, where T
is the type of x
, except that x
is evaluated only once.
- Otherwise, the compound assignment is invalid, and a binding-time error occurs.