Information Technology Reference
In-Depth Information
This code produces the following output:
sb: 208
Unhandled Exception: System.OverflowException: Arithmetic operation resulted
in an overflow. at Test1.Test.Main() in C:\Programs\Test1\Program.cs:line 21
The checked and unchecked Statements
The checked and unchecked operators , which you just looked at in the previous section, act
on the single expression between the parentheses. The checked and unchecked statements per-
form the same function, but control all the conversions in a block of code, rather than in a
single expression.
The checked and unchecked statements can be nested to any level.
For example, the following code uses checked and unchecked statements, and produces the
same results as the previous example, which uses checked and unchecked expressions. In this
case, however, blocks of code are affected, rather than just expressions.
byte sb;
ushort sh = 2000;
unchecked // Set unchecked
{
sb = (byte) sh;
Console.WriteLine("sb: {0}", sb);
checked // Set checked
{
sb = (byte) sh;
Console.WriteLine("sb: {0}", sh);
}
}
Search WWH ::




Custom Search