Program in C#:
short a, b;
a = 10;
b = 10;
a = a + b; // Error : Cannot implicitly convert type 'int' to 'short'.
// we can also write this code by using Arithmetic Assignment Operator as given below
a += b; // But this is running successfully, why?
Console.Write(a);
There are two questions here. The first is "why is short plus short result in int?"
Well, suppose short plus short was short and see what happens:
short[] prices = { 10000, 15000, 11000 };
short average = (prices[0] + prices[1] + prices[2]) / 3;
And the average is, of course, -9845 if this calculation is done in shorts. The sum is larger than the largest possible short, so it wraps around to negative, and then you divide the negative number.
In a world where integer arithmetic wraps around it is much more sensible to do all the calculations in int, a type which is likely to have enough range for typical calculations to not overflow.
The second question is:
The question has an incorrect premise; the third line above is wrong. The C# specification states in section 7.17.2
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.
The compiler inserts the cast on your behalf. The correct reasoning is:
If it did not insert the cast for you then it would be impossible to use compound assignment on many types.