How to use unchecked (no exceptions when overflow) and checked (add exceptions when overflow) in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            short x = 0;
            short y = 100;
            try
            {
                while (true)
                {
                    checked
                    {
                        x++; // overflow error exception
                    }
                    unchecked
                    {
                        y++; // cause no exceptions when overflow
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(x);
                Console.WriteLine(y);
                Console.WriteLine(ex);
            }
        }
    }
}

/*
run:

32767
-32669
System.OverflowException: Arithmetic operation resulted in an overflow.
   at ConsoleApplication_C_Sharp.Program.Main(String[] args) in d:\Conso
leApplication_C_Sharp\ConsoleApplication_C_Sharp\Program.cs:line 17

*/

 



answered Jan 19, 2017 by avibootz

Related questions

1 answer 153 views
1 answer 195 views
1 answer 214 views
1 answer 158 views
2 answers 427 views
1 answer 153 views
...