Thursday, 27 January 2011

Checked and Unchecked Keyword in .Net

    Checked Key word is used to enforce the compiler to check the buffer overflow while operating arithmetic operators. If there is any Buffer overflow code will throw exception.
     static void Main(string[] args)
            {
                int _value1 = 1500056564;
                int _value2 = 1200046565;
                checked
                {
    // this Code will give exception BuferOverflow
                            System.Console.WriteLine(_value1 * _value2);                System.Console.Read();
    }
    }
    Unchecked Keyword is used to enforce the compiler to do not check that is there any buffer overflow or Not. If here any Buffer overflow is occurred it will just truncate the value but not throw exception
    static void Main(string[] args)
            {
                int _value1 = 1500056564;
                             int _value2 = 1200046565;
                unchecked
                {
    // This Code will Not Give Exception
                 System.Console.WriteLine(_value1 * _value2);               
    System.Console.Read();
    }
    }

No comments:

Post a Comment