简体   繁体   中英

Int64 % Int32 gives Int64 result

long longVar = 100_000_000_000;
int intVar = int.MinValue;
long result = longVar % intVar;

In this example, why result should be long? It cannot be more than Int32.MaxValue, why it was decided to make remainder Int64 in this operation?

As per the C# specification only the following remainder operators are predefined for integer types:

int operator %(int x, int y);
uint operator %(uint x, uint y);
long operator %(long x, long y);
ulong operator %(ulong x, ulong y);

Hence in your case the compiler chooses the long(long, long) version, and casts intVar to long automatically. Then the result is of type long .

Because if you try to use Int32 in this situation will be OverflowException(maybe). And have any moments in which will be cast into bigger object. For example:

int firstNumber = 10;
long secondNumber = 100;
var result = firstNumber + secondNumber;

(result - long) If you don't believe me you can check.

This is due to the automatic cast to the parameter type of a specific method. In your case, this is '%'. In the case of the '+' sign, you can override the statement and specify your own implementation of this statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM