Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a modulo operator (%) result implicitly cast to the left side rather than the right side in C#?

Take the following code:

long longInteger = 42;
int normalInteger = 23;
object rem = longInteger % normalInteger;

If rem is the remainder of longInteger / normalInteger, shouldn't the remainder always be bounded by the smaller sized "int", the divisor? Yet in C#, the above code results in rem being a long.

Is it safe to convert rem to int without any loss of data?

int remainder = Convert.ToInt32(rem);
like image 309
jasonsirota Avatar asked Sep 12 '25 08:09

jasonsirota


1 Answers

There is no overload of the modulo operator that takes a long and an int, so the int will be converted to long to match the other operand.

Looking at it at a lower level, in the CPU there is no separate instruction for calculating modulo, it's just one of the results of the division operation. The output of the operation is the result of the division, and the reminder. Both are the same size, so as the result of the division has to be a long, so is the reminder.

As the reminder has to be smaller than the divisor, you can safely cast the result to int when the divisor comes from an int.

like image 109
Guffa Avatar answered Sep 14 '25 22:09

Guffa