0

I'm trying to execute a modulo operation with 2 numbers of type short :

short short1 = 1; // or any other short value
short short2 = 2;
short result = short1 % short2;

But I get this compilation error:

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

Why does the compiler think the result should be of type int?
The result must be between 0 and min(short1, short2) and both those values are short.

Idov
  • 5,006
  • 17
  • 69
  • 106
  • 1
    Take a look at the [C# language specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#remainder-operator) for the remainder operator - you'll see there is no definition of % for shorts, only ints. Becauase a short can fit inside an int, both your short1 and short2 are automatically upgraded to ints and the calculation is carried out using ints. This means your result is an int, which cannot then be back-assigned to a short without a cast because of the potential loss of information (int is larger than short) – Caius Jard Oct 17 '19 at 17:16

1 Answers1

1

In your case the short numbers are lifted to int before applying the module operator, since the remainder operator is not defined for types smaller than int.

So you have int int.operator %(int left, int right)and the return type is int.

You can explicitly cast to short since you know that the result is representable by a short.

short result = (short)(short1 % short2);
kkica
  • 4,034
  • 1
  • 20
  • 40