As developers knows that many arithmetic operations on primitives types could result in an overflow:

Byte b=100;
b=(Byte) (b+200);       //b now contains 44 (2c in hex)

In some cases silent overflow can give undesirable results, and if not detected causes the application to behave in strange and unusual ways. Many languages handles overflows in different ways. Like C and C++ allows overflow and is not considered as an error and allow the value to wrap; allows to application continues running. Microsoft visual basic always considers overflows to be an errors and throws an exception when it detects.

The common language runtime (CLR) offers IL (Intermediate language) instructions that allow the compiler to choose the desired behavior. as you know the C# compiler generated IL has an add instruction as it the default behavior for C# to generate silent overflow. C# compiler use the /checked+ compiler switch to control the overflow, which tell the C# compiler to uses the safe version of the add with overflow check , add.ovf which will prevent this kind of silent overflow and throw OverflowException if overflow occur.

C# allows the programmer to decide how overflow should be handled. as you know, By default overflow checking is turned off. this means that the compiler generates IL code by using the versions of the add, subtract, multiply, and conversion instructions that don't include overflow checking. as a result, the code runs faster but developers must be assured that overflows won't occur or that their code is designed to anticipate these overflows.

If overflow occur, the CLR throws an OverflowException. You should design your application's code to handle this exception. Rather than have overflow checking turned off on or off globally, C# allows this flexibility by offering checked and unchecked operators. Simply checked operator tells the C# compiler to use the safe IL instruction for this operation , and the unchecked use the normal IL instructions (which is the normal behavior in C#).

Here is an example that use checked operator:

Byte b=100;
b=checked((Byte)(b+200));                  //OverflowException is thrown

If the Byte cast outside the checked operator, the exception wouldn't be occurred.

b=(Byte)checked((b+200));                 //no OverflowException

In addition to the checked and unchecked operators, C# also offers checked and unchecked statements. the statements cause all expressions within a block to be checked or unchecked:

checked{
 Byte b=100;
 b=(Byte((b=200);
}

Now, try to turn on the compiler's switch /checked+ switch for debug build. Your application will run slowly because the system will be checking for overflow on any code that you didn't explicitly mark as checked and unchecked. If an exception occurs, you will be able to easily detect and be able to fix the bug in you application.



Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5