C# Numeric types Overflow


will this code be compiled?
int x= int.MaxValue;
x=x+1;   

The answer is, yes it will be compiled 









I will tell you how,

at runtime arithmetic operations on Integral types can overflow, and this happens silently no exceptions will be thrown, and the results exhibits wraparound behavior

that means 

int x= int.MaxValue;
x= x+1;
(x == int.MinValue) // True

and if we do also the below expressions it will not give you the right result

int a = 80000; 
int b = 80000; 
int c = a * b;  // 2105032704    

while the right result is 6,400,000,000

So to avoid this issue we will use Checked Operator

int a = 80000; 
int b = 80000; 
int c = checked(a * b);  // Run-time exception (line 9): Arithmetic operation resulted in an overflow

Checked:

The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type.

Note: The checked operator has no effect on the double and float types which overflow to special infinite values, and no effect on the decimal type (because it always checked)


Unchecked:

The unchecked operator does the opposite of Checked Operator, it disable the overflow checking even in the constant's expressions

int x= unchecked(int.MaxValue + 1);//-2147483648

References:

Comments

Popular posts from this blog

Sitecore Multi list Code Data Source

Organize media files using Sitecore PowerShell