Using checked Versus unchecked Statements - CSharp Language Basics

CSharp examples for Language Basics:checked unchecked

Introduction

If the code is checked and a value is placed in a variable that is too big or too small, an exception will occur.

If the code is unchecked, the value placed will be truncated to fit within the variable.

Demo Code

using System;//w w  w  . j  a  va  2  s .c  o m
class CheckIt
{
   public static void Main()
   {
      int result;
      const int topval = 2147483647;
      for( long i = topval - 5L;  i < (topval+10L); i++ )
      {
         checked
         {
            result = (int) i;
            Console.WriteLine("{0} assigned from {1}", result, i);
         }
      }
   }
}

Result


Related Tutorials