Checking Overflow in C#
When you use value type in your application for arithmetic operations, you will need to check the boundaries of data types after the operation completes every time i.e., have to ensure the value of data type does not exceeds the MaxValue of the data type, Overflow does not occur.Else you will get overflow Exception at runtime.
}
2. Using Checked/Unchecked Operators
3. Using Checked/Unchecked Statement
In addition to Checked Operators, C# provides Checked/Unchecked Statement. The statement cause all expressions within a block to be checked or unchecked.
And the following images/snapshot are correspondng IL instructions of above code.
If you see, you can find add.ovf and Conv.ovf IL instructions are generated inside a method body which is using Checked Statement. And simply add IL instruction is generated inside a method body which is using NOT using Checked Statement
Note :
1. If you have multiple overflow checks in your code, the code will execute little slow. Because the CLR is monitoring the arithmetic operations whether overflow has occurred.But still it is recommend to you use checked operators and use only where it is required.
2. Calling a method (which perform some Arith. operations) inside Checked/unchecked statement will not have any impact as the code block which contains.
Different languages treat this overflow in different Manner( C, C++ does not throw overflow exception rather wrap up the value, MS Visual Basic throws the Overflow Exception by default)
Whereas .Net does not check for the overflow exception until we explicitly we tell the CLR to check for Overflow Exception. By Default Overflow check is set off .
Let's see an Example :
{
short val = 32767;
short val = 32767;
val = (short)(val + 40000);
In above code, we try to add constant value to Val variable of short data type and error was expected when i ran the application. But Surprise, it runs with no Exception
But Why ?? Let's look depth how CLR encounter the Corresponding IL instructions.CLR has two different versions of IL instructions for Arithmetic operations such as Add, Multiple, Subtract and
etc.
Add : Add (), Add.ovf ()
Subtract : Sub (), Sub.ovf ()
Multiply : Mul (), Mul.ovf ()
Convert : Conv (), Conv.ovf ()
The Add Method which adds two value but it performs no overflow checking. And the another method Add.Ovf() which does the same operation, but it checks for overflow.
etc.
Add : Add (), Add.ovf ()
Subtract : Sub (), Sub.ovf ()
Multiply : Mul (), Mul.ovf ()
Convert : Conv (), Conv.ovf ()
The Add Method which adds two value but it performs no overflow checking. And the another method Add.Ovf() which does the same operation, but it checks for overflow.
The IL code generated by compiler using the versions of the add, subtract, multiply, and conversion instructions that dont include overflow checking by default. So the code runs faster but developers
must be assured that overflows wont occur at runtime and causing the running program to get terminated.
must be assured that overflows wont occur at runtime and causing the running program to get terminated.
How to intimate the C# compilers that OVF checking instructions should generated when we compile the program ?
.Net framework offers the solution in three ways and you can choose appropriate one as your require.
1. Using Checked Switch in Compiler/ VS command line parameter.Net framework offers the solution in three ways and you can choose appropriate one as your require.
2. Using Checked/Unchecked Operators
3. Using Checked/Unchecked Statement
Checked Switch :
This is kind of Global switch if it is set on, where the compiler will understand and generate code that has the overflow-checking versions of the add, subtract, multiply, and conversion IL instructions when you compile your project.
The disadvantage is the code executes a little slower because the CLR is checking these operations to determine whether an overflow occurred. If an overflow occurs, the CLR throws an Overflow Exception.
This switch can be set on using Visual studio, Go To Project properties, click advanced tab in BUILD section. Now you have to enable the option 'Check for Arithmetic overflow/underflow'.
The disadvantage is the code executes a little slower because the CLR is checking these operations to determine whether an overflow occurred. If an overflow occurs, the CLR throws an Overflow Exception.
This switch can be set on using Visual studio, Go To Project properties, click advanced tab in BUILD section. Now you have to enable the option 'Check for Arithmetic overflow/underflow'.
Look at the fig below :
Checked/ Unchecked Operators :
What if a programmer wants to enable/disable this overflow checking at only particular code region not at project level ? Here we go..
You can use Checked / Unchecked operators, which does the same operation as explained above. when compiler encounter these operators, compiler will generate appropriate version with overflow checking IL instructions instead of normal code to execute.
{
short val = 32767;
val = Checked((short)(val + 40000));
val = UnChecked((short)(val + 40000));
}
Since the Checked keyword is used in first statement, it performs overflow-checking and the Overflow exception will be thrown at runtime.The second statement does not perform overflow-checking and just ignores overflow and wrap up the value of data type.val = UnChecked((short)(val + 40000));
}
In addition to Checked Operators, C# provides Checked/Unchecked Statement. The statement cause all expressions within a block to be checked or unchecked.
E.g :
Checked
{
short val = 32767;
val = (short)(val + 40000);
.....
.....
}
Let's see how C# compiler chooses the versions of instruction using sample C# code which checks for overflow and will have look at corresponding IL code using .Net Reflector
In the following sample, there are two methods which adds passed two param value and return the sum of those values. But one of the method which checks for over flow and another method
(AddValueWithNoOverflowCheck) ignores the over flow check.
Let's see how C# compiler chooses the versions of instruction using sample C# code which checks for overflow and will have look at corresponding IL code using .Net Reflector
In the following sample, there are two methods which adds passed two param value and return the sum of those values. But one of the method which checks for over flow and another method
(AddValueWithNoOverflowCheck) ignores the over flow check.
Add Method with Checked Statement |
Add Method With no checked Statment |
And the following images/snapshot are correspondng IL instructions of above code.
IL Code Of Add Method which has Checked Statment |
IL Code of Add Method which does not Check Overflow |
Note :
2. Calling a method (which perform some Arith. operations) inside Checked/unchecked statement will not have any impact as the code block which contains.
Comments
Post a Comment