short can't arithmetic with constant?

  • Thread starter Thread starter sd
  • Start date Start date
S

sd

short Total=11;
short Index=Total-1;

will occurs the following error:

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

and this is correct:

short Index=(short)(Total-1);

A bit ugly...
 
sd,

11 and 1 are considered integers by the compiler. Trying to place an
integer in a short can result in a possible data loss, hence the compiler
warning.

You can also do this:

short Index = Total - ((short) 1);

And that should work.

Hope this helps.
 
.... and that's exactly what you have to do. Actually using int would be more
efficient believe it or not.
 
Back
Top