0

I am studing C# and this for me sound really strange... Why to add to short type I have to do an explicit conversion?

short x = 1, y = 1;
short z = x + y; // Compile-time error

Explicit Cast:

short z = (short) (x + y); // OK
overcomer
  • 2,244
  • 3
  • 26
  • 39
  • 1
    32000 + 32000. Both are short type but the result is more than what short can hold. + operator returns int so it can handle more than short values. You have to cast to store it in short again but it will throw exception if the value is more than short.maxvalue – M.kazem Akhgary Sep 28 '15 at 07:02
  • 1
    http://stackoverflow.com/questions/11853602/c-sharp-does-not-let-me-sum-two-shorts-to-a-short – Dmitry Bychenko Sep 28 '15 at 07:03

1 Answers1

1

that shows the compilation error because because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default. So you would need to do type casting.

It is possible though to use plus operand with other data types like long int double, where the destination variable has the same storage size or a larger storage size but as short has smaller size, so you can't use it directly.

amit dayama
  • 3,246
  • 2
  • 17
  • 28