Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short + short != short? [duplicate]

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)

like image 968
Aendie Avatar asked May 06 '15 13:05

Aendie


1 Answers

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.

like image 61
Saverio Terracciano Avatar answered Nov 06 '22 16:11

Saverio Terracciano