In C#, why can't we add int
to long
? Why does the compiler need implicit conversion from int
to long
to perform the operations?
Similar for byte
to short
or short
to int
: why is an implicit conversion required?
Can someone clearly explain the purpose of numeric promotions and binary promotions in C#
The reason is that the underlying CIL Add
instruction that the C# compiler must use for adding integral values requires that both values are the same size.
Therefore in order to use the Add
instruction to add two integral values of differing sizes, the C# compiler must emit CIL instructions to extend the smaller of the two values to be the same size as the larger.
An obvious follow-up question would be "But why doesn't CIL include instructions to add integral values of different sizes?". We can't answer that question - only the designers of CIL can answer why.
We can only guess: Maybe because it was not necessary to complicate the CIL instruction set and thus its implementation - and many processors lack an Add
instruction to add integral values of differing sizes so adding that to the CIL instruction set would provide no benefit.
However do note that the JIT compiler for a processor with an Add
instruction that worked with operands of different sizes could in theory detect such cases and emit the more efficient instructions, without any need for direct support in the CIL instruction set.