Posts

Showing posts with the label Integer

C# Integral Types That Lack Arithmetic Operations

Image
In C# there's some types that lack arithmetic operations These Integral types are 8 and 16 Bit so it's converted implicitly to the largest types, below is the list of these types : byte sbyte short ushort Sample of code: short a=10,b=10; short sum = a+b; // compile time error The solution: as mentioned a and b   variables   are implicitly  converted to the largest type "Int" , to solve this we have to use the explicit casting on the total result: short a=10,b=10; short sum = (short)(a+b); // compiled successfully References: Microsoft

C# Numeric types Overflow

Image
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 ...