anar khalilov
anar khalilov

Reputation: 17498

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.

Upvotes: 4

Views: 147

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062620

  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

Upvotes: 8

Related Questions