Checking For Overflow - CSharp Language Basics

CSharp examples for Language Basics:checked unchecked

Description

Checking For Overflow

Demo Code

using System;/*  www .  j  ava  2  s .c  o m*/
using static System.Console;
class Program
{
   static void Main(string[] args)
   {
      try
      {
         checked
         {
            int x = int.MaxValue - 1;
            WriteLine(x);
            x++;
            WriteLine(x);
            x++;
            WriteLine(x);
            x++;
            WriteLine(x);
         }
      }
      catch (OverflowException)
      {
         WriteLine("The code overflowed but I caught the exception.");
      }
      unchecked
      {
         int y = int.MaxValue + 1;
         WriteLine(y); // this will output -2147483648
         y--;
         WriteLine(y); // this will output 2147483647
         y--;
         WriteLine(y); // this will output 2147483646
      }
   }
}

Result


Related Tutorials