6.6 Overflow Detection Using Checked and Unchecked

 <  Day Day Up  >  

You want to allow or disallow overflows of integral types to occur.


Technique

Overflow detection works by placing an expression to evaluate within parentheses prefixed with the checked or unchecked keyword. If you specify unchecked , an integral value will overflow without an exception being thrown. If you specify checked and an integral type overflows, a System.OverflowException is thrown. If you use neither of the keywords, overflow detection is based on the current project build settings. Listing 6.5 demonstrates the use of the checked and unchecked keyword, as shown in the overloaded multiplication operator defined in the Counter class.

Listing 6.5 Overflow Detection Using the Checked Keyword
 using System; namespace _6_CheckedUnchecked {     class Class1     {         [STAThread]         static void Main(string[] args)         {             // create 2 counters. One is checked, the other is not             Counter counter1 = new Counter( 1, false );             Counter counter2 = new Counter( 1, true );             // overflow detection disabled             for( int i = 1; i < 15; i++ )             {                 // overflow will occur                 counter1 *= i;                 Console.WriteLine( counter1.Value );             }             try             {                 // overflow detection enabled                 for( int i = 1; i < 15; i++ )                 {                     // an exception is thrown when overflow occurs                     counter2 *= i;                     Console.WriteLine( counter2.Value );                 }             }             catch( Exception e )             {                 Console.WriteLine( "Exception caught: {0}", e.Message );             }         }     }     class Counter     {         public int Value = 0;         public bool EnableCheck = false;         // passing true in second parameter will enable overflow detection         public Counter( int val, bool enableCheck )         {             this.Value = val;             this.EnableCheck = enableCheck;         }         public static Counter operator * ( Counter op1, int op2 )         {             int newVal;             if( op1.EnableCheck )                 newVal = checked( op1.Value * op2 );             else                 newVal = unchecked( op1.Value * op2 );             return new Counter( newVal, op1.EnableCheck );         }     } } 

To enable overflow detection without using the checked keyword on each expression, select Project, Properties from the main menu. Navigate to the Configuration Properties, Build property page and set "Check for Arithmetic Overflow/Underflow" to true to enable checking or false to disable checking. By default, this setting is false , as shown in Figure 6.3.

Figure 6.3. Change project-wide overflow detection by changing your project's build settings.

graphics/06fig03.gif

Comments

A variable that overflows can be a subtle defect that can have very undesirable side effects. It can be hard to track down without the aid of a debugger or programmatic debugging techniques. However, the C# language coupled with the C# compiler makes overflow detection an easy task.

You use the checked and unchecked keywords to check the result of an expression that works with integral types. In Listing 6.5, you can see a simple class named Counter that has an overloaded multiplication operator. This operator simply multiplies the current value of a Counter instance by a specified integer. If the Boolean value EnableCheck is true within the instance of the class, then overflow detection is enabled when the multiplication is performed. Likewise, if EnableCheck is false , then overflow detection is disabled. The Main method creates two loops that repeatedly multiply the value of two instances of the Counter class, with one instance checking for overflow conditions and the other not. Furthermore, because an overflow throws an exception if it is being checked, an exception handler is used to catch the exception. The results of running Listing 6.5 appear in Figure 6.4.

Figure 6.4. The Counter value will overflow if unchecked, as shown in the last value of the first set, but an exception occurs in the second set.

graphics/06fig04.gif

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net