Sunday, July 22, 2007

Checked and Unchecked Keyword

Checked:
Checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations
Expressions insode a Checked block can throw a compile time error in event of an overflow of expression has constants, else System.OverflowException is thrown
Unchecked:
Expressions inside an unchecked block do not throw exception
Unchecked keyword is used to suppress overflow checking
Result is truncated to fit into destination type to avoid overflow

Code Listing: Unchecked

unchecked
{
int val = 2147483123 * 2;
}

This will cause an overflow, as result wont fit in int
No error/exception is reported and result is truncated to fit in int

No comments: