Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit cast of long/decimal to 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 longMaxValue to int results in -1?

Question #2: Why casting decimalMaxValue to int results in the following exception BUT casting longMaxValue to int doesn't?

Value was either too large or too small for an Int32.

like image 686
anar khalilov Avatar asked Feb 11 '23 23:02

anar khalilov


1 Answers

  1. because long.MaxValue is binary 0111111....1111; casting here basically cuts it down to the last (least significant) 32 bits - all of which are 1; and binary 111...111 is: -1

  2. integer arithmetic is unchecked in C# by default. Add checked, or change the compiler to check by default, and it will error

like image 63
Marc Gravell Avatar answered Feb 15 '23 09:02

Marc Gravell