Short + short! = Short?

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

I do not understand the error in the following C # code:

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

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

It is not possible to implicitly convert the type 'int' to 'short'. Explicit conversion exists (are you skipping listing?)

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 adding in the form of "short + Int32 constant" seems to work, and the result is Int32, which needs to be dropped for short.

Is there an explanation why the first code example fails or is it a compiler error? (which I hardly believe after 4 updates)

+6
source share
1 answer

Int is the smallest type of signed type for which the + operator is given, so we try to use + for short-term results of this kind of error.

+3
source

Source: https://habr.com/ru/post/986657/


All Articles