using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DataAndOperators
{
    class Examples32_37
    {
        public static void ImplicitConversions()
        {
            // Listing 2-32
            int i = 42;
            double di = i;
            Console.WriteLine(i / 5);
            Console.WriteLine(di / 5);
            Console.WriteLine(i / 5.0); 
        }

        //// Kod umieszczony w komentarzach gdyż ilustruje błąd
        //public static void BadImplicitConversions()
        //{
        //    // Listing 2-33
        //    int i = 42;
        //    int willFail = 42.0;
        //    int willAlsoFail = i / 1.0;
        //}

        public static void ExplicitConversions()
        {
            // Listing 2-34
            int i = 42;
            int i2 = (int) 42.0;
            int i3 = (int) (i / 1.0);

            Console.WriteLine(i2);
            Console.WriteLine(i3);
        }

        public static void ExploitingUnderflow()
        {
            int start = Environment.TickCount;
            DoSomeWork();
            int end = Environment.TickCount;

            int totalTicks = end - start;
            Console.WriteLine(totalTicks);
        }

        private static void DoSomeWork()
        {
            Thread.Sleep(750);
        }

        public static void CheckedExpression()
        {
            int a = 0x70000000;
            int b = 0x60000000;
            int c = 10;
            try
            {
                // Listing 2-36
                int result = checked(a + b) + c; 
            }
            catch (Exception x)
            {
                Console.WriteLine(x);
            }

            try
            {
                // Listing 2-37
                checked
                {
                    int r1 = a + b;
                    int r2 = r1 - (int) c;
                }
            }
            catch (Exception x)
            {
                Console.WriteLine(x);
            }
        }
    }
}
