Explicit listing of long / decimal for int

Consider the following code:

long longMaxValue = long.MaxValue;
decimal decimalMaxValue = decimal.MaxValue;

int a = (int)longMaxValue;
int b = (int)decimalMaxValue;

Question # 1: Why casting longMaxValueup intleads to -1?

Question # 2: Why casting decimalMaxValuein intleads to the following exception. BUT listing longMaxValue- intnot?

The value was too large or too small for Int32.

+4
source share
1 answer
  • because it long.MaxValueis binary 0111111 .... 1111; casting here basically reduces it to the last (least significant) 32 bit - all of which are 1; and binary 111 ... 111: -1

  • unchecked # . checked ,

+8

All Articles