7

Version: Visual Studio Professional 2013 Update 4
Build param: Prefer 32-bit is true

I don't understand the error in the following C# code:

short iCount = 20;
short iValue = iCount + (short)1;

Adding a short to an int casted to a short results in the following error:

Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

The above error, also seen in the following case, is perfectly valid here:

short iCount = 20;
short iValue = iCount + 1;

The following workaround removes the error:

short iCount = 20;
short iValue = (short)(iCount + 1);

So addition in the form "short + Int32 constant" apparently works and the result is Int32, which needs to be cast to a short.

Is there an explanation why the first code sample fails or is this a compiler bug? (which I can hardly believe after 4 Updates)

Aendie
  • 321
  • 1
  • 13
  • Take a look at this [answer](http://stackoverflow.com/questions/7504837/why-is-my-addition-of-2-shorts-causing-a-casting-compile-error-due-to-ints) – Bobby Tables May 06 '15 at 13:17
  • [Related](http://stackoverflow.com/a/3080381/335858) – Sergey Kalinichenko May 06 '15 at 13:18
  • [Related](http://stackoverflow.com/questions/11853602/c-sharp-does-not-let-me-sum-two-shorts-to-a-short) – weston May 06 '15 at 13:18
  • also related: http://stackoverflow.com/questions/10065287/why-is-ushort-ushort-equal-to-int – Habib May 06 '15 at 13:20
  • Modern architectures are built for 32- or 64-bit arithmetic. It's simply more efficient for the `+` operator to "promote" 16-bit int's to 32-bit and then do 32-bit addition, with a 32-bit result. Though perhaps unexpected, it is by design, as specified in the [C# reference](https://msdn.microsoft.com/en-us/library/aa691329%28v=vs.71%29.aspx). – Arin May 06 '15 at 13:21
  • However if the expression is constant (known at compile-time), the conversion from `int` to `short` is "free". As in: `const int iCount = 20; short iValue = iCount + 1;` Note that both summands are of type `int`, so clearly the sum is an `int` too, but the conversion from `int` to `short` is implicit in these cases. – Jeppe Stig Nielsen May 06 '15 at 13:28

1 Answers1

4

Int is the smallest signed type for which the + operator is defined, so trying to use + on a short results in that kind of error.

Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
  • Interesting! A more complete answer can be found [here](http://stackoverflow.com/questions/4343624/integer-summing-blues-short-short-problem/4347752#4347752) – Gimly May 06 '15 at 13:19