I am going to explain about the Checked Operator available in C#.NET to handle the integer overflow. ProblemIn my order management system, I have to calculate sales point for the each customer who places an order. This sales points are integer values which get earned by customer based on the product they purchase and get deducted from the account as they purchase new product using these points. But there are some customers who are not aware of point system or not consuming these points so that the value of point gets increased more than the limit of the integer values i.e., 2^32 . So whenever calculation takes place, I receive some junk value for those customers who are having point value more than integer value, i.e. 2^32. SolutionTo avoid this issue of overflow of integer value and to inform customer who is having more points, I came across a Checked Operator of C#.NET. Checked Operator for Checking for Overflow in Mathematical Operations and conversions for the integer types. SyntaxChecked( expression ) ss or Checked { statements...... } Example Collapsepublic static void Main()
{int a;int b;int c;
a = 2000000000;
b = 2000000000;
c = checked(a+ b);
System.Console.WriteLine(Int1PlusInt2);
}When we run the above code, it throws an exception as below: CollapseException occurred: System.OverflowException: An exception of type
System.OverflowException was thrown. which tells that c value is more than the integer type length. Same way in my application, I catch the overflow exception when thrown when calculating the order points and then raise mail to customer that you have to utilise the point you have, otherwise you will lose the points after end of xyz period and display point as maxvalue+ . |