Unchecked keyword PDF Print E-mail
User Rating: / 0
PoorBest 
Monday, 09 March 2009
HTML clipboard

The unchecked keyword is designed to control the overflow-checking for integral-type operations and any conversions you may be doing. You can use unchecked as either a operator or a statement.

Statement:

unchecked block

Operator:

unchecked (expression)

Where:

  • block - the entire block that contains the expressions is to be evaluated in an unchecked context
  • expression - a expression (in parentheses) is to be evaluated in a unchecked context only

Key Points:

The default overflow checking is checked (i.e you can either explicitly write checked or do nothing and it will implicitly be treated as checked), which means you will receive a "The operation overflows at compile time in checked mode". If on the other hand you specifiy unchecked in either the statement block or expression then the expression will be truncated (if it falls outside the range of the destination type).

Example:

public void Page_Load(object sender, EventArgs e)
{
   Response.Write(UncheckedTest());
}
public int UncheckedTest()
{
    // Unchecked used as a statement
    // Without this statement you will get the following error:
    // CS0220: The operation overflows at compile time in checked mode
    unchecked
    {
         // max int value multiplied by 2
         // which usually overflows
         int total = 2147483647 * 2;  
         return total;
    }
}

 
< Prev   Next >
School Joomla Templates and Joomla Tutorials