Pranay Rana: Checked Operator

Saturday, February 12, 2011

Checked Operator

In following post I am going to explain about the Checked Operator available in C#.Net to handle the integer overflow.

Problem
In my order management system I have to calculate sales point for the each customer who place order. This sales points are integer values which get earn by customer based on the product they purchase and get deducted from the account as they purchase new product using this points. But there are some customer who are not aware of point system or not consuming this points so that the value of point get increase more than the limit of the integer values i.e 2^32 . So when ever calculation take place I receive some junk value for those customers who are having point value more than integer value i.e 2^32.

Solution
To avoid this issue of over flow 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 ingeger types.
Syntax
Checked( expression )
or
Checked { statements...... }

Example
public static void Main()
  {
   int a;
   int b;
   int c;
    
   a = 2000000000;
   b = 2000000000;
   c = checked(a+ b);
   System.Console.WriteLine(Int1PlusInt2);
  }
When we run above code, it throws exception as below

Exception 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 than 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 maxvlaue+ .

No comments:

Post a Comment