Behind the Scenes Look at C#: Type Conversions - The Checked and Unchecked Keywords
(Page 6 of 6 )
The checked code blocks checks for arithmetic ranges overflow. When an overflow happens, the Common Language Runtime throws an exception of type System.OverflowException. This is useful when you perform explicit cast operations to ensure that the values are in the valid ranges.
The unchecked code block doesn't check for arithmetic overflow. When an overflow happens, no runtime exceptions will be thrown. The value will be truncated, and this is what may yield the unexpected values we are talking about. Take a look at the following example.
using System;
namespace TypeConversion
{
class Class1
{
static void Main(string[] args)
{
short x = 300; // greater than the maximum of byte
byte y = (byte)x;
Console.WriteLine("The result of casting x to byte and storing the value in y = {0}", y);
Console.ReadLine();
}
}
}
The result that you will get to the console window is

y equals to 44? Unexpected, right? Actually it's all about bits, as I said before. The short data type (Int32) uses two bytes to store the value. In our example the value is 300, which means 00000001 00101100. When we cast it to the byte data type (which uses only 1 byte to store its value), the bits representation is 00101100, which equals 44; there is no magic involved here.
Let's use the checked block and see the result. We used the unchecked block in the above example because it's the default behavior with the compiler options, so you can just omit it and you will get the same result.
using System;
namespace TypeConversion
{
class Class1
{
static void Main(string[] args)
{
checked
{
short x = 300; // greater than the maximum of byte
byte y = (byte)x;
Console.WriteLine("The result of casting x to byte and storing the value in y = {0}", y);
Console.ReadLine();
}
}
}
}
This time the application throws a runtime exception of type System.OverflowException because the value of x is 300, and it's greater than the maximum range of the byte data type. I guess an exception is better than an unexpected value, right?
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |