I do understand why this produce compile time-error:
short x = 1;
short y = 2;
short z = x + y; // compile-time error
I've grasped why this runs without any issues:
short x = 1;
short y = 2;
x += y; // all right, because of c# specs section 7.17.2
But I've got no clue why this also works:
short x = (short)1 + (short)2;
I expected to get the same compile-time error as in the first example, but it runs successfully... Why?
Since you're using constant values, the compiler can detect that it's allowable, evaluate it at compile time, and let it execute. The generated IL evaluates to the same as typing short x = 3;
.
Note the following also works (for the same reason):
const short x = 1;
const short y = 2;
short z = x + y;
But this fails:
const short x = 32000;
const short y = 32001;
short z = x + y;
Note that this is covered in the C# Language Spec, 6.1.9 Implicit constant expression conversions: