Unchecked and checked words are used to control whether or not an overflow occurred during arithmetic operations.
Overflows: When a value exceeds the limitations of a data type, it is said to overflow. This can be an inconvenience where unexpected, causing incorrect results from calculations.
Checked Arithmetic : To prevent the incorrect or dangerous results of unchecked calculations, checked arithmetic can be used instead. One way to achieve this is to use the "checked" keyword for specific sections of code. This keyword uses a code block to surround a series of items that should be processed in this way. If an overflow occurs within a checked code block, an exception of the type System.OverflowException is thrown.
In the above code snippet you can see that I have tried to add extra value to the "z" variable which is of "int" data type and it can hold only "2147483647" value.
This is somewhat we were not expecting your expectation was the compiler should throw some error (overflow) or exception.
Let add Checked Keyword and see what happen inside program.
After adding checked keyword , we can able to see overflow exception in program.
Unchecked Arithmetic : When using the default C# compiler options, arithmetic is unchecked. This means that any overflowing data from arithmetic operations is simply truncated. In the following sample code this is demonstrated by setting an integer to its maximum value, then incrementing it. The resultant value is truncated and rather than being a larger number is actually the smallest permissible integer value.
Let see below screen shoot .
As we can see its work like before it was . we not getting any exception now.
No comments:
Post a Comment